ScriptDocument.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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 MethodInfo method;
  41. private object obj;
  42. private Type type;
  43. static ScriptDocument()
  44. {
  45. DefaultAssemblies = new FluentList<Assembly>()
  46. .Add(typeof(object).Assembly)
  47. .Add(typeof(Regex).Assembly)
  48. .Add(typeof(List<>).Assembly)
  49. .Add(typeof(Enumerable).Assembly)
  50. .Add(typeof(Bitmap).Assembly)
  51. .Add(typeof(Expression).Assembly);
  52. }
  53. public ScriptDocument(string text)
  54. {
  55. if (Host == null)
  56. Initialize();
  57. Text = text;
  58. Properties = new List<ScriptProperty>();
  59. }
  60. public static RoslynHost Host { get; private set; }
  61. public static FluentList<Assembly> DefaultAssemblies { get; }
  62. public Script<object> Script { get; private set; }
  63. public string Text
  64. {
  65. get => _text;
  66. set => SetProperty(ref _text, value);
  67. }
  68. public DocumentId Id { get; set; }
  69. public string Result
  70. {
  71. get => _result;
  72. private set => SetProperty(ref _result, value);
  73. }
  74. private static MethodInfo HasSubmissionResult { get; } =
  75. typeof(Compilation).GetMethod(nameof(HasSubmissionResult), BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
  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. public bool Execute(string classname = "Module", string methodname = "Execute", object[] parameters = null)
  158. {
  159. var result = false;
  160. if (!compiled.HasValue)
  161. {
  162. compiled = false;
  163. var stream = new MemoryStream();
  164. var emitResult = Script.GetCompilation().Emit(stream);
  165. if (emitResult.Success)
  166. {
  167. var asm = Assembly.Load(stream.ToArray());
  168. type = asm.GetTypes().Where(x => x.Name.Equals(classname)).FirstOrDefault();
  169. if (type != null)
  170. {
  171. obj = Activator.CreateInstance(type);
  172. compiled = true;
  173. }
  174. }
  175. }
  176. if (compiled.Value)
  177. {
  178. foreach (var property in Properties)
  179. {
  180. var prop = type.GetProperty(property.Name);
  181. if (prop != null)
  182. prop.SetValue(obj, property.Value);
  183. }
  184. method = type.GetMethod(methodname);
  185. if (method != null)
  186. {
  187. if (method.ReturnType == typeof(bool))
  188. {
  189. result = (bool)(method.Invoke(obj, parameters ?? Array.Empty<object>()) ?? false);
  190. }
  191. else
  192. {
  193. method.Invoke(obj, parameters ?? Array.Empty<object>());
  194. result = true;
  195. }
  196. if (result)
  197. foreach (var property in Properties)
  198. {
  199. var prop = type.GetProperty(property.Name);
  200. if (prop != null)
  201. property.Value = prop.GetValue(obj);
  202. }
  203. }
  204. else
  205. {
  206. result = false;
  207. }
  208. }
  209. return result;
  210. }
  211. private static string FormatException(Exception ex)
  212. {
  213. return CSharpObjectFormatter.Instance.FormatException(ex);
  214. }
  215. private static string FormatObject(object o)
  216. {
  217. return CSharpObjectFormatter.Instance.FormatObject(o, PrintOptions);
  218. }
  219. protected bool SetProperty<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
  220. {
  221. if (!EqualityComparer<T>.Default.Equals(field, value))
  222. {
  223. field = value;
  224. // ReSharper disable once ExplicitCallerInfoArgument
  225. OnPropertyChanged(propertyName);
  226. return true;
  227. }
  228. return false;
  229. }
  230. protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
  231. {
  232. PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  233. }
  234. public static bool RunCustomModule(DataModel model, Dictionary<string, object[]> selected, string code)
  235. {
  236. var script = new ScriptDocument(code);
  237. if (!script.Compile())
  238. {
  239. throw new CompileException();
  240. }
  241. script.SetValue("Data", selected);
  242. script.SetValue("Model", model);
  243. script.Execute(methodname: "BeforeLoad");
  244. var tableNames = model.DefaultTableNames.ToList();
  245. script.Execute(methodname: "CheckTables", parameters: new[] { tableNames });
  246. model.LoadModel(tableNames);
  247. return script.Execute();
  248. }
  249. }
  250. }