ScriptDocument.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Drawing;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Linq.Expressions;
  8. using System.Reflection;
  9. using System.Runtime.CompilerServices;
  10. using System.Text.RegularExpressions;
  11. using System.Threading;
  12. using InABox.Core;
  13. using Microsoft.CodeAnalysis;
  14. using Microsoft.CodeAnalysis.CSharp.Scripting;
  15. using Microsoft.CodeAnalysis.CSharp.Scripting.Hosting;
  16. using Microsoft.CodeAnalysis.Scripting;
  17. using Microsoft.CodeAnalysis.Scripting.Hosting;
  18. using RoslynPad.Roslyn;
  19. namespace InABox.Scripting;
  20. public class ScriptProperty : Dictionary<string, object>
  21. {
  22. public ScriptProperty(string name, object? value)
  23. {
  24. Name = name;
  25. Value = value;
  26. }
  27. public string Name { get; set; }
  28. public object? Value { get; set; }
  29. }
  30. public class CompileException : Exception
  31. {
  32. public CompileException() : base("Unable to compile script!") { }
  33. }
  34. public class ScriptDocument : INotifyPropertyChanged
  35. {
  36. private string _result;
  37. private string _text = "";
  38. private bool? compiled;
  39. private object? obj;
  40. private Type? type;
  41. static ScriptDocument()
  42. {
  43. DefaultAssemblies = new FluentList<Assembly>()
  44. .Add(typeof(object).Assembly)
  45. .Add(typeof(Regex).Assembly)
  46. .Add(typeof(List<>).Assembly)
  47. .Add(typeof(Enumerable).Assembly)
  48. .Add(typeof(Bitmap).Assembly)
  49. .Add(typeof(Expression).Assembly);
  50. }
  51. public ScriptDocument(string text)
  52. {
  53. if (Host == null)
  54. Initialize();
  55. Text = text;
  56. Properties = new List<ScriptProperty>();
  57. }
  58. public static RoslynHost Host { get; private set; }
  59. public static FluentList<Assembly> DefaultAssemblies { get; }
  60. public Script<object> Script { get; private set; }
  61. public string Text
  62. {
  63. get => _text;
  64. set => SetProperty(ref _text, value);
  65. }
  66. public DocumentId Id { get; set; }
  67. public string Result
  68. {
  69. get => _result;
  70. private set => SetProperty(ref _result, value);
  71. }
  72. private static MethodInfo HasSubmissionResult { get; } =
  73. typeof(Compilation).GetMethod(nameof(HasSubmissionResult), BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
  74. ?? throw new NullReferenceException();
  75. private static PrintOptions PrintOptions { get; } = new() { MemberDisplayFormat = MemberDisplayFormat.SeparateLines };
  76. public List<ScriptProperty> Properties { get; }
  77. public event PropertyChangedEventHandler? PropertyChanged;
  78. private static IEnumerable<MetadataReference> CompilationReferences;
  79. public static void Initialize()
  80. {
  81. var typelist = CoreUtils.TypeList(
  82. AppDomain.CurrentDomain.GetAssemblies(),
  83. x =>
  84. x.GetTypeInfo().IsClass
  85. && !x.GetTypeInfo().IsGenericType
  86. && x.GetTypeInfo().IsSubclassOf(typeof(BaseObject))).ToList();
  87. for (var i = typelist.Count - 1; i > -1; i--) // var type in typelist)
  88. {
  89. var type = typelist[i];
  90. var module = type.Assembly.Modules.FirstOrDefault();
  91. if (module != null && !module.FullyQualifiedName.Equals("<Unknown>"))
  92. DefaultAssemblies.Add(type.Assembly);
  93. else
  94. typelist.RemoveAt(i);
  95. }
  96. var references = Directory.GetFiles(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "refs"), "*.dll")
  97. .Select(x => MetadataReference.CreateFromFile(x)).ToArray();
  98. var files = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll").Where(
  99. x => !Path.GetFileName(x).ToLower().StartsWith("gsdll")
  100. && !Path.GetFileName(x).ToLower().StartsWith("pdfium")
  101. && !Path.GetFileName(x).ToLower().StartsWith("ikvm-native")
  102. && !Path.GetFileName(x).ToLower().StartsWith("sqlite.interop")
  103. && !Path.GetFileName(x).ToLower().StartsWith("microsoft.codeanalysis")
  104. );
  105. var hostReferences = RoslynHostReferences.NamespaceDefault.With(
  106. typeNamespaceImports: typelist
  107. //, assemblyReferences: DefaultAssemblies
  108. , assemblyPathReferences: files,
  109. references: references
  110. );
  111. CompilationReferences = RoslynHostReferences.NamespaceDefault.With(
  112. typeNamespaceImports: typelist
  113. , assemblyReferences: DefaultAssemblies
  114. , assemblyPathReferences: files
  115. ).GetReferences();
  116. Host = new RoslynHost(
  117. DefaultAssemblies.ToArray(),
  118. hostReferences
  119. );
  120. }
  121. public bool Compile()
  122. {
  123. Result = null;
  124. compiled = null;
  125. Script = CSharpScript.Create(Text, ScriptOptions.Default
  126. .AddReferences(CompilationReferences)
  127. .AddImports(Host.DefaultImports));
  128. var compilation = Script.GetCompilation();
  129. var hasResult = (bool)HasSubmissionResult.Invoke(compilation, null);
  130. var diagnostics = Script.Compile();
  131. if (diagnostics.Any(t => t.Severity == DiagnosticSeverity.Error))
  132. {
  133. var result = new List<string>();
  134. var errors = diagnostics.Select(FormatObject).Where(x => x.StartsWith("CSDiagnostic("));
  135. foreach (var error in errors)
  136. result.Add(
  137. error.Split(new[] { Environment.NewLine }, StringSplitOptions.None).First().Replace("CSDiagnostic(", "").Replace(") {", ""));
  138. Result = string.Join(Environment.NewLine, result);
  139. return false;
  140. }
  141. return true;
  142. }
  143. public void SetValue(string name, object value)
  144. {
  145. var prop = Properties.FirstOrDefault(x => x.Name.Equals(name));
  146. if (prop == null)
  147. Properties.Add(new ScriptProperty(name, value));
  148. else
  149. prop.Value = value;
  150. }
  151. public object? GetValue(string name, object? defaultvalue = null)
  152. {
  153. var prop = Properties.FirstOrDefault(x => x.Name.Equals(name));
  154. return prop != null ? prop.Value : defaultvalue;
  155. }
  156. private Type? GetClassType(string className = "Module")
  157. {
  158. if (!compiled.HasValue)
  159. {
  160. compiled = false;
  161. var stream = new MemoryStream();
  162. var emitResult = Script.GetCompilation().Emit(stream);
  163. if (emitResult.Success)
  164. {
  165. var asm = Assembly.Load(stream.ToArray());
  166. type = asm.GetTypes().Where(x => x.Name.Equals(className)).FirstOrDefault();
  167. if (type != null)
  168. {
  169. obj = Activator.CreateInstance(type);
  170. compiled = true;
  171. }
  172. }
  173. }
  174. return type;
  175. }
  176. public object? GetObject(string className = "Module")
  177. {
  178. GetClassType(className);
  179. return obj;
  180. }
  181. public MethodInfo? GetMethod(string className = "Module", string methodName = "Execute")
  182. {
  183. var type = GetClassType(className);
  184. if (compiled == true && type != null)
  185. {
  186. return type.GetMethod(methodName);
  187. }
  188. else
  189. {
  190. return null;
  191. }
  192. }
  193. public bool Execute(string classname = "Module", string methodname = "Execute", object[]? parameters = null, bool defaultResult = false)
  194. {
  195. var result = defaultResult;
  196. var type = GetClassType(classname);
  197. var obj = GetObject(classname);
  198. var method = GetMethod(classname, methodname);
  199. if (compiled == true && type != null && method != null)
  200. {
  201. foreach (var property in Properties)
  202. {
  203. var prop = type.GetProperty(property.Name);
  204. prop?.SetValue(obj, property.Value);
  205. }
  206. if (method.ReturnType == typeof(bool))
  207. {
  208. result = (bool)(method.Invoke(obj, parameters ?? Array.Empty<object>()) ?? false);
  209. }
  210. else
  211. {
  212. method.Invoke(obj, parameters ?? Array.Empty<object>());
  213. result = true;
  214. }
  215. if (result)
  216. {
  217. foreach (var property in Properties)
  218. {
  219. var prop = type.GetProperty(property.Name);
  220. if (prop != null)
  221. property.Value = prop.GetValue(obj);
  222. }
  223. }
  224. }
  225. return result;
  226. }
  227. private static string FormatException(Exception ex)
  228. {
  229. return CSharpObjectFormatter.Instance.FormatException(ex);
  230. }
  231. private static string FormatObject(object o)
  232. {
  233. return CSharpObjectFormatter.Instance.FormatObject(o, PrintOptions);
  234. }
  235. protected bool SetProperty<T>(ref T field, T value, [CallerMemberName] string? propertyName = null)
  236. {
  237. if (!EqualityComparer<T>.Default.Equals(field, value))
  238. {
  239. field = value;
  240. // ReSharper disable once ExplicitCallerInfoArgument
  241. OnPropertyChanged(propertyName);
  242. return true;
  243. }
  244. return false;
  245. }
  246. protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
  247. {
  248. PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  249. }
  250. public static bool RunCustomModule(DataModel model, Dictionary<string, object[]> selected, string code)
  251. {
  252. var script = new ScriptDocument(code);
  253. if (!script.Compile())
  254. {
  255. throw new CompileException();
  256. }
  257. script.SetValue("Data", selected);
  258. script.SetValue("Model", model);
  259. script.Execute(methodname: "BeforeLoad");
  260. var tableNames = model.DefaultTableNames.ToList();
  261. script.Execute(methodname: "CheckTables", parameters: new[] { tableNames });
  262. model.LoadModel(tableNames);
  263. return script.Execute();
  264. }
  265. }