ScriptDocument.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Linq.Expressions;
  7. using System.Reflection;
  8. using System.Runtime.CompilerServices;
  9. using System.Text.RegularExpressions;
  10. using System.Threading;
  11. using InABox.Core;
  12. using Microsoft.CodeAnalysis;
  13. using Microsoft.CodeAnalysis.CSharp.Scripting;
  14. using Microsoft.CodeAnalysis.CSharp.Scripting.Hosting;
  15. using Microsoft.CodeAnalysis.Scripting;
  16. using Microsoft.CodeAnalysis.Scripting.Hosting;
  17. using RoslynPad.Roslyn;
  18. namespace InABox.Scripting
  19. {
  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 MethodInfo method;
  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(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. private static PrintOptions PrintOptions { get; } = new() { MemberDisplayFormat = MemberDisplayFormat.SeparateLines };
  75. public List<ScriptProperty> Properties { get; }
  76. public event PropertyChangedEventHandler PropertyChanged;
  77. private static IEnumerable<MetadataReference> CompilationReferences;
  78. public static void Initialize()
  79. {
  80. var typelist = CoreUtils.TypeList(
  81. AppDomain.CurrentDomain.GetAssemblies(),
  82. x =>
  83. x.GetTypeInfo().IsClass
  84. && !x.GetTypeInfo().IsGenericType
  85. && x.GetTypeInfo().IsSubclassOf(typeof(BaseObject))).ToList();
  86. for (var i = typelist.Count - 1; i > -1; i--) // var type in typelist)
  87. {
  88. var type = typelist[i];
  89. var module = type.Assembly.Modules.FirstOrDefault();
  90. if (module != null && !module.FullyQualifiedName.Equals("<Unknown>"))
  91. DefaultAssemblies.Add(type.Assembly);
  92. else
  93. typelist.RemoveAt(i);
  94. }
  95. var references = Directory.GetFiles(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "refs"), "*.dll")
  96. .Select(x => MetadataReference.CreateFromFile(x)).ToArray();
  97. var files = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll").Where(
  98. x => !Path.GetFileName(x).ToLower().StartsWith("gsdll")
  99. && !Path.GetFileName(x).ToLower().StartsWith("pdfium")
  100. && !Path.GetFileName(x).ToLower().StartsWith("ikvm-native")
  101. && !Path.GetFileName(x).ToLower().StartsWith("sqlite.interop")
  102. && !Path.GetFileName(x).ToLower().StartsWith("microsoft.codeanalysis")
  103. );
  104. var hostReferences = RoslynHostReferences.NamespaceDefault.With(
  105. typeNamespaceImports: typelist
  106. //, assemblyReferences: DefaultAssemblies
  107. , assemblyPathReferences: files,
  108. references: references
  109. );
  110. CompilationReferences = RoslynHostReferences.NamespaceDefault.With(
  111. typeNamespaceImports: typelist
  112. , assemblyReferences: DefaultAssemblies
  113. , assemblyPathReferences: files
  114. ).GetReferences();
  115. Host = new RoslynHost(
  116. DefaultAssemblies.ToArray(),
  117. hostReferences
  118. );
  119. }
  120. public bool Compile()
  121. {
  122. Result = null;
  123. compiled = null;
  124. Script = CSharpScript.Create(Text, ScriptOptions.Default
  125. .AddReferences(CompilationReferences)
  126. .AddImports(Host.DefaultImports));
  127. var compilation = Script.GetCompilation();
  128. var hasResult = (bool)HasSubmissionResult.Invoke(compilation, null);
  129. var diagnostics = Script.Compile();
  130. if (diagnostics.Any(t => t.Severity == DiagnosticSeverity.Error))
  131. {
  132. var result = new List<string>();
  133. var errors = diagnostics.Select(FormatObject).Where(x => x.StartsWith("CSDiagnostic("));
  134. foreach (var error in errors)
  135. result.Add(
  136. error.Split(new[] { Environment.NewLine }, StringSplitOptions.None).First().Replace("CSDiagnostic(", "").Replace(") {", ""));
  137. Result = string.Join(Environment.NewLine, result);
  138. return false;
  139. }
  140. return true;
  141. }
  142. public void SetValue(string name, object value)
  143. {
  144. var prop = Properties.FirstOrDefault(x => x.Name.Equals(name));
  145. if (prop == null)
  146. Properties.Add(new ScriptProperty(name, value));
  147. else
  148. prop.Value = value;
  149. }
  150. public object GetValue(string name, object defaultvalue = null)
  151. {
  152. var prop = Properties.FirstOrDefault(x => x.Name.Equals(name));
  153. return prop != null ? prop.Value : defaultvalue;
  154. }
  155. public bool Execute(string classname = "Module", string methodname = "Execute", object[] parameters = null)
  156. {
  157. var result = false;
  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. if (compiled.Value)
  175. {
  176. foreach (var property in Properties)
  177. {
  178. var prop = type.GetProperty(property.Name);
  179. if (prop != null)
  180. prop.SetValue(obj, property.Value);
  181. }
  182. method = type.GetMethod(methodname);
  183. if (method != null)
  184. {
  185. if (method.ReturnType == typeof(bool))
  186. {
  187. result = (bool)method.Invoke(obj, parameters != null ? parameters : new object[] { });
  188. }
  189. else
  190. {
  191. method.Invoke(obj, parameters != null ? parameters : new object[] { });
  192. result = true;
  193. }
  194. if (result)
  195. foreach (var property in Properties)
  196. {
  197. var prop = type.GetProperty(property.Name);
  198. if (prop != null)
  199. property.Value = prop.GetValue(obj);
  200. }
  201. }
  202. else
  203. {
  204. result = false;
  205. }
  206. }
  207. return result;
  208. }
  209. private static string FormatException(Exception ex)
  210. {
  211. return CSharpObjectFormatter.Instance.FormatException(ex);
  212. }
  213. private static string FormatObject(object o)
  214. {
  215. return CSharpObjectFormatter.Instance.FormatObject(o, PrintOptions);
  216. }
  217. protected bool SetProperty<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
  218. {
  219. if (!EqualityComparer<T>.Default.Equals(field, value))
  220. {
  221. field = value;
  222. // ReSharper disable once ExplicitCallerInfoArgument
  223. OnPropertyChanged(propertyName);
  224. return true;
  225. }
  226. return false;
  227. }
  228. protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
  229. {
  230. PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  231. }
  232. public static bool RunCustomModule(DataModel model, Dictionary<string, object[]> selected, string code)
  233. {
  234. var script = new ScriptDocument(code);
  235. if (!script.Compile())
  236. {
  237. throw new CompileException();
  238. }
  239. script.SetValue("Data", selected);
  240. script.SetValue("Model", model);
  241. script.Execute(methodname: "BeforeLoad");
  242. var tableNames = model.DefaultTableNames.ToList();
  243. script.Execute(methodname: "CheckTables", parameters: new[] { tableNames });
  244. model.LoadModel(tableNames);
  245. return script.Execute();
  246. }
  247. }
  248. }