Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 10747 was 10731, checked in by abeham, 11 years ago

#2136:

  • Split Script into Script and CSharpScript
  • Split ScriptView into ScriptView and CSharpScriptView
File size: 5.5 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    protected 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 = new VariableStore();
81    }
82    public CSharpScript() {
83      variableStore = new VariableStore();
84    }
85    public CSharpScript(string code)
86      : base(code) {
87      variableStore = new VariableStore();
88    }
89
90    public override IDeepCloneable Clone(Cloner cloner) {
91      return new CSharpScript(this, cloner);
92    }
93    #endregion
94
95    protected virtual void RegisterScriptEvents() {
96      if (CompiledScript != null)
97        CompiledScript.ConsoleOutputChanged += CompiledScriptOnConsoleOutputChanged;
98    }
99
100    protected virtual void DeregisterScriptEvents() {
101      if (CompiledScript != null)
102        CompiledScript.ConsoleOutputChanged -= CompiledScriptOnConsoleOutputChanged;
103    }
104
105    #region Compilation
106
107    public override Assembly Compile() {
108      CompiledScript = null;
109      var assembly = base.Compile();
110      var types = assembly.GetTypes();
111      DeregisterScriptEvents();
112      CompiledScript = (CSharpScriptBase)Activator.CreateInstance(types.First(x => typeof(CSharpScriptBase).IsAssignableFrom(x)));
113      RegisterScriptEvents();
114      return assembly;
115    }
116    #endregion
117
118    protected Thread ScriptThread;
119    public virtual void Execute() {
120      if (CompiledScript == null) return;
121      var executeMethod = typeof(CSharpScriptBase).GetMethod(ExecuteMethodName, BindingFlags.NonPublic | BindingFlags.Instance);
122      if (executeMethod != null) {
123        ScriptThread = new Thread(() => {
124          Exception ex = null;
125          try {
126            OnScriptExecutionStarted();
127            executeMethod.Invoke(CompiledScript, new object[] { VariableStore });
128          } catch (ThreadAbortException) {
129            // the execution was cancelled by the user
130          } catch (TargetInvocationException e) {
131            ex = e.InnerException;
132          } finally {
133            OnScriptExecutionFinished(ex);
134          }
135        });
136        ScriptThread.Start();
137      }
138    }
139
140    public virtual void Kill() {
141      if (ScriptThread.IsAlive)
142        ScriptThread.Abort();
143    }
144
145    protected virtual void CompiledScriptOnConsoleOutputChanged(object sender, EventArgs<string> e) {
146      OnConsoleOutputChanged(e.Value);
147    }
148
149    public event EventHandler ScriptExecutionStarted;
150    protected virtual void OnScriptExecutionStarted() {
151      var handler = ScriptExecutionStarted;
152      if (handler != null) handler(this, EventArgs.Empty);
153    }
154
155    public event EventHandler<EventArgs<Exception>> ScriptExecutionFinished;
156    protected virtual void OnScriptExecutionFinished(Exception e) {
157      var handler = ScriptExecutionFinished;
158      if (handler != null) handler(this, new EventArgs<Exception>(e));
159    }
160
161    public event EventHandler<EventArgs<string>> ConsoleOutputChanged;
162    protected virtual void OnConsoleOutputChanged(string args) {
163      var handler = ConsoleOutputChanged;
164      if (handler != null) handler(this, new EventArgs<string>(args));
165    }
166  }
167}
Note: See TracBrowser for help on using the repository browser.