using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using System.Threading; using InABox.Core; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Scripting; using Microsoft.CodeAnalysis.CSharp.Scripting.Hosting; using Microsoft.CodeAnalysis.Scripting; using Microsoft.CodeAnalysis.Scripting.Hosting; using RoslynPad.Roslyn; namespace InABox.Scripting { public class ScriptProperty : Dictionary { public ScriptProperty(string name, object value) { Name = name; Value = value; } public string Name { get; set; } public object Value { get; set; } } public class CompileException : Exception { public CompileException() : base("Unable to compile script!") { } } public class ScriptDocument : INotifyPropertyChanged { private string _result; private string _text = ""; private bool? compiled; private MethodInfo method; private object obj; private Type type; static ScriptDocument() { DefaultAssemblies = new FluentList() .Add(typeof(object).Assembly) .Add(typeof(Regex).Assembly) .Add(typeof(List<>).Assembly) .Add(typeof(Enumerable).Assembly) .Add(typeof(Bitmap).Assembly) .Add(typeof(Expression).Assembly); } public ScriptDocument(string text) { if (Host == null) Initialize(); Text = text; Properties = new List(); } public static RoslynHost Host { get; private set; } public static FluentList DefaultAssemblies { get; } public Script Script { get; private set; } public string Text { get => _text; set => SetProperty(ref _text, value); } public DocumentId Id { get; set; } public string Result { get => _result; private set => SetProperty(ref _result, value); } private static MethodInfo HasSubmissionResult { get; } = typeof(Compilation).GetMethod(nameof(HasSubmissionResult), BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); private static PrintOptions PrintOptions { get; } = new() { MemberDisplayFormat = MemberDisplayFormat.SeparateLines }; public List Properties { get; } public event PropertyChangedEventHandler PropertyChanged; private static IEnumerable CompilationReferences; public static void Initialize() { var typelist = CoreUtils.TypeList( AppDomain.CurrentDomain.GetAssemblies(), x => x.GetTypeInfo().IsClass && !x.GetTypeInfo().IsGenericType && x.GetTypeInfo().IsSubclassOf(typeof(BaseObject))).ToList(); for (var i = typelist.Count - 1; i > -1; i--) // var type in typelist) { var type = typelist[i]; var module = type.Assembly.Modules.FirstOrDefault(); if (module != null && !module.FullyQualifiedName.Equals("")) DefaultAssemblies.Add(type.Assembly); else typelist.RemoveAt(i); } var references = Directory.GetFiles(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "refs"), "*.dll") .Select(x => MetadataReference.CreateFromFile(x)).ToArray(); var files = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll").Where( x => !Path.GetFileName(x).ToLower().StartsWith("gsdll") && !Path.GetFileName(x).ToLower().StartsWith("pdfium") && !Path.GetFileName(x).ToLower().StartsWith("ikvm-native") && !Path.GetFileName(x).ToLower().StartsWith("sqlite.interop") && !Path.GetFileName(x).ToLower().StartsWith("microsoft.codeanalysis") ); var hostReferences = RoslynHostReferences.NamespaceDefault.With( typeNamespaceImports: typelist //, assemblyReferences: DefaultAssemblies , assemblyPathReferences: files, references: references ); CompilationReferences = RoslynHostReferences.NamespaceDefault.With( typeNamespaceImports: typelist , assemblyReferences: DefaultAssemblies , assemblyPathReferences: files ).GetReferences(); Host = new RoslynHost( DefaultAssemblies.ToArray(), hostReferences ); } public bool Compile() { Result = null; compiled = null; Script = CSharpScript.Create(Text, ScriptOptions.Default .AddReferences(CompilationReferences) .AddImports(Host.DefaultImports)); var compilation = Script.GetCompilation(); var hasResult = (bool)HasSubmissionResult.Invoke(compilation, null); var diagnostics = Script.Compile(); if (diagnostics.Any(t => t.Severity == DiagnosticSeverity.Error)) { var result = new List(); var errors = diagnostics.Select(FormatObject).Where(x => x.StartsWith("CSDiagnostic(")); foreach (var error in errors) result.Add( error.Split(new[] { Environment.NewLine }, StringSplitOptions.None).First().Replace("CSDiagnostic(", "").Replace(") {", "")); Result = string.Join(Environment.NewLine, result); return false; } return true; } public void SetValue(string name, object value) { var prop = Properties.FirstOrDefault(x => x.Name.Equals(name)); if (prop == null) Properties.Add(new ScriptProperty(name, value)); else prop.Value = value; } public object GetValue(string name, object defaultvalue = null) { var prop = Properties.FirstOrDefault(x => x.Name.Equals(name)); return prop != null ? prop.Value : defaultvalue; } public bool Execute(string classname = "Module", string methodname = "Execute", object[] parameters = null) { var result = false; if (!compiled.HasValue) { compiled = false; var stream = new MemoryStream(); var emitResult = Script.GetCompilation().Emit(stream); if (emitResult.Success) { var asm = Assembly.Load(stream.ToArray()); type = asm.GetTypes().Where(x => x.Name.Equals(classname)).FirstOrDefault(); if (type != null) { obj = Activator.CreateInstance(type); compiled = true; } } } if (compiled.Value) { foreach (var property in Properties) { var prop = type.GetProperty(property.Name); if (prop != null) prop.SetValue(obj, property.Value); } method = type.GetMethod(methodname); if (method != null) { if (method.ReturnType == typeof(bool)) { result = (bool)method.Invoke(obj, parameters != null ? parameters : new object[] { }); } else { method.Invoke(obj, parameters != null ? parameters : new object[] { }); result = true; } if (result) foreach (var property in Properties) { var prop = type.GetProperty(property.Name); if (prop != null) property.Value = prop.GetValue(obj); } } else { result = false; } } return result; } private static string FormatException(Exception ex) { return CSharpObjectFormatter.Instance.FormatException(ex); } private static string FormatObject(object o) { return CSharpObjectFormatter.Instance.FormatObject(o, PrintOptions); } protected bool SetProperty(ref T field, T value, [CallerMemberName] string propertyName = null) { if (!EqualityComparer.Default.Equals(field, value)) { field = value; // ReSharper disable once ExplicitCallerInfoArgument OnPropertyChanged(propertyName); return true; } return false; } protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public static bool RunCustomModule(DataModel model, Dictionary selected, string code) { var script = new ScriptDocument(code); if (!script.Compile()) { throw new CompileException(); } script.SetValue("Data", selected); script.SetValue("Model", model); script.Execute(methodname: "BeforeLoad"); var tableNames = model.DefaultTableNames.ToList(); script.Execute(methodname: "CheckTables", parameters: new[] { tableNames }); model.LoadModel(tableNames); return script.Execute(); } } }