Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Scripting/3.3/Script.cs @ 10727

Last change on this file since 10727 was 10727, checked in by jkarder, 10 years ago

#2136:

  • fixed tool tips
  • added Clear() method to remove all variables present in the VariableStore
  • the script cannot be compiled and started with the shortcuts anymore if it is already running
File size: 9.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.CodeDom;
24using System.CodeDom.Compiler;
25using System.Collections.Generic;
26using System.Drawing;
27using System.IO;
28using System.Linq;
29using System.Reflection;
30using System.Text;
31using System.Text.RegularExpressions;
32using System.Threading;
33using HeuristicLab.Common;
34using HeuristicLab.Common.Resources;
35using HeuristicLab.Core;
36using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
37using Microsoft.CSharp;
38
39namespace HeuristicLab.Scripting {
40  [Item("C# Script", "An empty C# script.")]
41  [Creatable("Scripts")]
42  [StorableClass]
43  public sealed class Script : NamedItem, IStorableContent {
44    #region Constants
45    private const string ExecuteMethodName = "Execute";
46    private const string CodeTemplate =
47@"// use 'vars' to access variables in the script's variable store (e.g. vars.x = 5)
48// use 'vars.Contains(string)' to check if a variable exists
49// use 'vars.Clear()' to remove all variables
50// use 'foreach (KeyValuePair<string, object> v in vars) { ... }' to iterate over all variables
51
52using System;
53using System.Linq;
54using System.Collections.Generic;
55using HeuristicLab.Common;
56using HeuristicLab.Core;
57using HeuristicLab.Data;
58
59public class UserScript : HeuristicLab.Scripting.UserScriptBase {
60  public override void Main() {
61    // type your code here
62  }
63
64  // implement further classes and methods
65
66}";
67    #endregion
68
69    #region Fields & Properties
70    private UserScriptBase compiledScript;
71
72    public string Filename { get; set; }
73
74    public static new Image StaticItemImage {
75      get { return VSImageLibrary.Script; }
76    }
77
78    [Storable]
79    private VariableStore variableStore;
80    public VariableStore VariableStore {
81      get { return variableStore; }
82    }
83
84    [Storable]
85    private string code;
86    public string Code {
87      get { return code; }
88      set {
89        if (value == code) return;
90        code = value;
91        compiledScript = null;
92        OnCodeChanged();
93      }
94    }
95
96    private string compilationUnitCode;
97    public string CompilationUnitCode {
98      get { return compilationUnitCode; }
99    }
100
101    private CompilerErrorCollection compileErrors;
102    public CompilerErrorCollection CompileErrors {
103      get { return compileErrors; }
104      private set {
105        compileErrors = value;
106        OnCompileErrorsChanged();
107      }
108    }
109    #endregion
110
111    #region Construction & Initialization
112    [StorableConstructor]
113    private Script(bool deserializing) : base(deserializing) { }
114    private Script(Script original, Cloner cloner)
115      : base(original, cloner) {
116      code = original.code;
117      variableStore = new VariableStore();
118      compilationUnitCode = original.compilationUnitCode;
119      if (original.compileErrors != null)
120        compileErrors = new CompilerErrorCollection(original.compileErrors);
121    }
122    public Script() {
123      name = ItemName;
124      description = ItemDescription;
125      code = CodeTemplate;
126      variableStore = new VariableStore();
127    }
128    public Script(string code)
129      : this() {
130      this.code = code;
131    }
132
133    public override IDeepCloneable Clone(Cloner cloner) {
134      return new Script(this, cloner);
135    }
136    #endregion
137
138    private void RegisterScriptEvents() {
139      if (compiledScript == null) return;
140      compiledScript.ConsoleOutputChanged += compiledScript_ConsoleOutputChanged;
141    }
142
143    private void DeregisterScriptEvents() {
144      if (compiledScript == null) return;
145      compiledScript.ConsoleOutputChanged -= compiledScript_ConsoleOutputChanged;
146    }
147
148    #region Compilation
149    private CSharpCodeProvider codeProvider =
150      new CSharpCodeProvider(
151        new Dictionary<string, string> {
152          { "CompilerVersion", "v4.0" },  // support C# 4.0 syntax
153        });
154
155    private CompilerResults DoCompile() {
156      var parameters = new CompilerParameters {
157        GenerateExecutable = false,
158        GenerateInMemory = true,
159        IncludeDebugInformation = true,
160        WarningLevel = 4
161      };
162      parameters.ReferencedAssemblies.AddRange(
163        GetAssemblies()
164        .Select(a => a.Location)
165        .ToArray());
166      var unit = CreateCompilationUnit();
167      var writer = new StringWriter();
168      codeProvider.GenerateCodeFromCompileUnit(
169        unit,
170        writer,
171        new CodeGeneratorOptions {
172          ElseOnClosing = true,
173          IndentString = "  ",
174        });
175      compilationUnitCode = writer.ToString();
176      return codeProvider.CompileAssemblyFromDom(parameters, unit);
177    }
178
179    public void Compile() {
180      var results = DoCompile();
181      compiledScript = null;
182      CompileErrors = results.Errors;
183      if (results.Errors.HasErrors) {
184        var sb = new StringBuilder();
185        foreach (CompilerError error in results.Errors) {
186          sb.Append(error.Line).Append(':')
187            .Append(error.Column).Append(": ")
188            .AppendLine(error.ErrorText);
189        }
190        throw new Exception(string.Format(
191          "Compilation of \"{0}\" failed:{1}{2}",
192          Name, Environment.NewLine,
193          sb.ToString()));
194      } else {
195        var assembly = results.CompiledAssembly;
196        var types = assembly.GetTypes();
197        DeregisterScriptEvents();
198        compiledScript = (UserScriptBase)Activator.CreateInstance(types[0]);
199        RegisterScriptEvents();
200      }
201    }
202
203    public IEnumerable<Assembly> GetAssemblies() {
204      var assemblies = new List<Assembly>();
205      foreach (var a in AppDomain.CurrentDomain.GetAssemblies()) {
206        try {
207          if (File.Exists(a.Location)) assemblies.Add(a);
208        } catch (NotSupportedException) {
209          // NotSupportedException is thrown while accessing
210          // the Location property of the anonymously hosted
211          // dynamic methods assembly, which is related to
212          // LINQ queries
213        }
214      }
215      assemblies.Add(typeof(Microsoft.CSharp.RuntimeBinder.Binder).Assembly); // for dlr functionality
216      return assemblies;
217    }
218
219    private readonly Regex SafeTypeNameCharRegex = new Regex("[_a-zA-Z0-9]+");
220    private readonly Regex SafeTypeNameRegex = new Regex("[_a-zA-Z][_a-zA-Z0-9]*");
221
222    private CodeCompileUnit CreateCompilationUnit() {
223      var unit = new CodeSnippetCompileUnit(code);
224      return unit;
225    }
226
227    public string CompiledTypeName {
228      get {
229        var sb = new StringBuilder();
230        var strings = SafeTypeNameCharRegex.Matches(Name)
231                                           .Cast<Match>()
232                                           .Select(m => m.Value);
233        foreach (string s in strings)
234          sb.Append(s);
235        return SafeTypeNameRegex.Match(sb.ToString()).Value;
236      }
237    }
238    #endregion
239
240    private Thread scriptThread;
241    public void Execute() {
242      if (compiledScript == null) return;
243      var executeMethod = typeof(UserScriptBase).GetMethod(ExecuteMethodName, BindingFlags.NonPublic | BindingFlags.Instance);
244      if (executeMethod != null) {
245        scriptThread = new Thread(() => {
246          Exception ex = null;
247          try {
248            OnScriptExecutionStarted();
249            executeMethod.Invoke(compiledScript, new[] { VariableStore });
250          } catch (ThreadAbortException) {
251            // the execution was cancelled by the user
252          } catch (TargetInvocationException e) {
253            ex = e.InnerException;
254          } finally {
255            OnScriptExecutionFinished(ex);
256          }
257        });
258        scriptThread.Start();
259      }
260    }
261
262    public void Kill() {
263      if (scriptThread.IsAlive)
264        scriptThread.Abort();
265    }
266
267    private void compiledScript_ConsoleOutputChanged(object sender, EventArgs<string> e) {
268      OnConsoleOutputChanged(e.Value);
269    }
270
271    public event EventHandler CodeChanged;
272    private void OnCodeChanged() {
273      var handler = CodeChanged;
274      if (handler != null) handler(this, EventArgs.Empty);
275    }
276
277    public event EventHandler CompileErrorsChanged;
278    private void OnCompileErrorsChanged() {
279      var handler = CompileErrorsChanged;
280      if (handler != null) handler(this, EventArgs.Empty);
281    }
282
283    public event EventHandler ScriptExecutionStarted;
284    private void OnScriptExecutionStarted() {
285      var handler = ScriptExecutionStarted;
286      if (handler != null) handler(this, EventArgs.Empty);
287    }
288
289    public event EventHandler<EventArgs<Exception>> ScriptExecutionFinished;
290    private void OnScriptExecutionFinished(Exception e) {
291      var handler = ScriptExecutionFinished;
292      if (handler != null) handler(this, new EventArgs<Exception>(e));
293    }
294
295    public event EventHandler<EventArgs<string>> ConsoleOutputChanged;
296    private void OnConsoleOutputChanged(string args) {
297      var handler = ConsoleOutputChanged;
298      if (handler != null) handler(this, new EventArgs<string>(args));
299    }
300  }
301}
Note: See TracBrowser for help on using the repository browser.