source: trunk/sources/HeuristicLab.Scripting/3.3/CSharpScript.cs @ 11734

Last change on this file since 11734 was 11734, checked in by jkarder, 6 years ago

#2262:

  • only IDeepCloneables can be dropped on the VariableStoreView
  • renamed CSharpScript.Execute to CSharpScript.ExecuteAsync
File size: 4.8 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 { get { return ReadCodeTemplate("HeuristicLab.Scripting.CSharpScriptCode.cs"); } }
38    #endregion
39
40    #region Fields & Properties
41    private CSharpScriptBase compiledScript;
42
43    public string Filename { get; set; }
44
45    [Storable]
46    private VariableStore variableStore;
47    public VariableStore VariableStore {
48      get { return variableStore; }
49    }
50    #endregion
51
52    #region Construction & Initialization
53    [StorableConstructor]
54    protected CSharpScript(bool deserializing) : base(deserializing) { }
55    protected CSharpScript(CSharpScript original, Cloner cloner)
56      : base(original, cloner) {
57      variableStore = cloner.Clone(original.variableStore);
58    }
59    public CSharpScript() {
60      variableStore = new VariableStore();
61      Code = CodeTemplate;
62    }
63    public CSharpScript(string code)
64      : base(code) {
65      variableStore = new VariableStore();
66    }
67
68    public override IDeepCloneable Clone(Cloner cloner) {
69      return new CSharpScript(this, cloner);
70    }
71    #endregion
72
73    protected virtual void RegisterScriptEvents() {
74      if (compiledScript != null)
75        compiledScript.ConsoleOutputChanged += CompiledScriptOnConsoleOutputChanged;
76    }
77
78    protected virtual void DeregisterScriptEvents() {
79      if (compiledScript != null)
80        compiledScript.ConsoleOutputChanged -= CompiledScriptOnConsoleOutputChanged;
81    }
82
83    #region Compilation
84
85    public override Assembly Compile() {
86      DeregisterScriptEvents();
87      compiledScript = null;
88      var assembly = base.Compile();
89      var types = assembly.GetTypes();
90      compiledScript = (CSharpScriptBase)Activator.CreateInstance(types.Single(x => typeof(CSharpScriptBase).IsAssignableFrom(x)));
91      RegisterScriptEvents();
92      return assembly;
93    }
94    #endregion
95
96    private Thread scriptThread;
97    public virtual void ExecuteAsync() {
98      if (compiledScript == null) return;
99      scriptThread = new Thread(() => {
100        Exception ex = null;
101        try {
102          OnScriptExecutionStarted();
103          compiledScript.Execute(VariableStore);
104        } catch (ThreadAbortException) {
105          // the execution was cancelled by the user
106        } catch (Exception e) {
107          ex = e;
108        } finally {
109          OnScriptExecutionFinished(ex);
110        }
111      });
112      scriptThread.SetApartmentState(ApartmentState.STA);
113      scriptThread.Start();
114    }
115
116    public virtual void Kill() {
117      if (scriptThread.IsAlive)
118        scriptThread.Abort();
119    }
120
121    protected virtual void CompiledScriptOnConsoleOutputChanged(object sender, EventArgs<string> e) {
122      OnConsoleOutputChanged(e.Value);
123    }
124
125    public event EventHandler ScriptExecutionStarted;
126    protected virtual void OnScriptExecutionStarted() {
127      var handler = ScriptExecutionStarted;
128      if (handler != null) handler(this, EventArgs.Empty);
129    }
130
131    public event EventHandler<EventArgs<Exception>> ScriptExecutionFinished;
132    protected virtual void OnScriptExecutionFinished(Exception e) {
133      var handler = ScriptExecutionFinished;
134      if (handler != null) handler(this, new EventArgs<Exception>(e));
135    }
136
137    public event EventHandler<EventArgs<string>> ConsoleOutputChanged;
138    protected virtual void OnConsoleOutputChanged(string args) {
139      var handler = ConsoleOutputChanged;
140      if (handler != null) handler(this, new EventArgs<string>(args));
141    }
142  }
143}
Note: See TracBrowser for help on using the repository browser.