Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 11857 was 11154, checked in by abeham, 10 years ago

#2209: merged to stable

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