source: stable/HeuristicLab.Scripting/3.3/CSharpScript.cs @ 11090

Last change on this file since 11090 was 11090, checked in by abeham, 5 years ago

#2203: merged to stable

File size: 5.3 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.Linq;
24using System.Reflection;
25using System.Threading;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
29
30namespace HeuristicLab.Scripting {
31  [Item("C# Script", "An empty C# script.")]
32  [Creatable("Scripts")]
33  [StorableClass]
34  public class CSharpScript : Script, IStorableContent {
35    #region Constants
36    protected const string ExecuteMethodName = "Execute";
37    protected override string CodeTemplate {
38      get {
39        return @"// use 'vars' to access variables in the script's variable store (e.g. vars.x = 5)
40// use 'vars.Contains(string)' to check if a variable exists
41// use 'vars.Clear()' to remove all variables
42// use 'foreach (KeyValuePair<string, object> v in vars) { ... }' to iterate over all variables
43
44using System;
45using System.Linq;
46using System.Collections.Generic;
47using HeuristicLab.Common;
48using HeuristicLab.Core;
49using HeuristicLab.Data;
50
51public class MyScript : HeuristicLab.Scripting.CSharpScriptBase {
52  public override void Main() {
53    // type your code here
54  }
55
56  // implement further classes and methods
57
58}";
59      }
60    }
61    #endregion
62
63    #region Fields & Properties
64    private CSharpScriptBase compiledScript;
65
66    public string Filename { get; set; }
67
68    [Storable]
69    private VariableStore variableStore;
70    public VariableStore VariableStore {
71      get { return variableStore; }
72    }
73    #endregion
74
75    #region Construction & Initialization
76    [StorableConstructor]
77    protected CSharpScript(bool deserializing) : base(deserializing) { }
78    protected CSharpScript(CSharpScript original, Cloner cloner)
79      : base(original, cloner) {
80      variableStore = cloner.Clone(original.variableStore);
81    }
82    public CSharpScript() {
83      variableStore = new VariableStore();
84      Code = CodeTemplate;
85    }
86    public CSharpScript(string code)
87      : base(code) {
88      variableStore = new VariableStore();
89    }
90
91    public override IDeepCloneable Clone(Cloner cloner) {
92      return new CSharpScript(this, cloner);
93    }
94    #endregion
95
96    protected virtual void RegisterScriptEvents() {
97      if (compiledScript != null)
98        compiledScript.ConsoleOutputChanged += CompiledScriptOnConsoleOutputChanged;
99    }
100
101    protected virtual void DeregisterScriptEvents() {
102      if (compiledScript != null)
103        compiledScript.ConsoleOutputChanged -= CompiledScriptOnConsoleOutputChanged;
104    }
105
106    #region Compilation
107
108    public override Assembly Compile() {
109      DeregisterScriptEvents();
110      compiledScript = null;
111      var assembly = base.Compile();
112      var types = assembly.GetTypes();
113      compiledScript = (CSharpScriptBase)Activator.CreateInstance(types.Single(x => typeof(CSharpScriptBase).IsAssignableFrom(x)));
114      RegisterScriptEvents();
115      return assembly;
116    }
117    #endregion
118
119    private Thread scriptThread;
120    public virtual void Execute() {
121      if (compiledScript == null) return;
122      scriptThread = new Thread(() => {
123        Exception ex = null;
124        try {
125          OnScriptExecutionStarted();
126          compiledScript.Execute(VariableStore);
127        } catch (ThreadAbortException) {
128          // the execution was cancelled by the user
129        } catch (Exception e) {
130          ex = e;
131        } finally {
132          OnScriptExecutionFinished(ex);
133        }
134      });
135      scriptThread.Start();
136    }
137
138    public virtual void Kill() {
139      if (scriptThread.IsAlive)
140        scriptThread.Abort();
141    }
142
143    protected virtual void CompiledScriptOnConsoleOutputChanged(object sender, EventArgs<string> e) {
144      OnConsoleOutputChanged(e.Value);
145    }
146
147    public event EventHandler ScriptExecutionStarted;
148    protected virtual void OnScriptExecutionStarted() {
149      var handler = ScriptExecutionStarted;
150      if (handler != null) handler(this, EventArgs.Empty);
151    }
152
153    public event EventHandler<EventArgs<Exception>> ScriptExecutionFinished;
154    protected virtual void OnScriptExecutionFinished(Exception e) {
155      var handler = ScriptExecutionFinished;
156      if (handler != null) handler(this, new EventArgs<Exception>(e));
157    }
158
159    public event EventHandler<EventArgs<string>> ConsoleOutputChanged;
160    protected virtual void OnConsoleOutputChanged(string args) {
161      var handler = ConsoleOutputChanged;
162      if (handler != null) handler(this, new EventArgs<string>(args));
163    }
164  }
165}
Note: See TracBrowser for help on using the repository browser.