ScriptDocument.cs 11 KB

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