Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ALPS/HeuristicLab.Scripting/3.3/CSharpScript.cs @ 11584

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

#2262:

  • IEnumerable<T> extension methods are supported by the variables collection
  • INamedItem variables get the item's name per default
  • variables can be renamed by pressing F2
  • variables are removed faster
  • multiple variables can be selected
  • the code editor supports scrolling while scripts are executed
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[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// use 'variables' to work with IEnumerable<T> extension methods on the script's variable store
45
46using System;
47using System.Linq;
48using System.Collections.Generic;
49using HeuristicLab.Common;
50using HeuristicLab.Core;
51using HeuristicLab.Data;
52
53public class MyScript : HeuristicLab.Scripting.CSharpScriptBase {
54  public override void Main() {
55    // type your code here
56  }
57
58  // implement further classes and methods
59
60}";
61      }
62    }
63    #endregion
64
65    #region Fields & Properties
66    private CSharpScriptBase compiledScript;
67
68    public string Filename { get; set; }
69
70    [Storable]
71    private VariableStore variableStore;
72    public VariableStore VariableStore {
73      get { return variableStore; }
74    }
75    #endregion
76
77    #region Construction & Initialization
78    [StorableConstructor]
79    protected CSharpScript(bool deserializing) : base(deserializing) { }
80    protected CSharpScript(CSharpScript original, Cloner cloner)
81      : base(original, cloner) {
82      variableStore = cloner.Clone(original.variableStore);
83    }
84    public CSharpScript() {
85      variableStore = new VariableStore();
86      Code = CodeTemplate;
87    }
88    public CSharpScript(string code)
89      : base(code) {
90      variableStore = new VariableStore();
91    }
92
93    public override IDeepCloneable Clone(Cloner cloner) {
94      return new CSharpScript(this, cloner);
95    }
96    #endregion
97
98    protected virtual void RegisterScriptEvents() {
99      if (compiledScript != null)
100        compiledScript.ConsoleOutputChanged += CompiledScriptOnConsoleOutputChanged;
101    }
102
103    protected virtual void DeregisterScriptEvents() {
104      if (compiledScript != null)
105        compiledScript.ConsoleOutputChanged -= CompiledScriptOnConsoleOutputChanged;
106    }
107
108    #region Compilation
109
110    public override Assembly Compile() {
111      DeregisterScriptEvents();
112      compiledScript = null;
113      var assembly = base.Compile();
114      var types = assembly.GetTypes();
115      compiledScript = (CSharpScriptBase)Activator.CreateInstance(types.Single(x => typeof(CSharpScriptBase).IsAssignableFrom(x)));
116      RegisterScriptEvents();
117      return assembly;
118    }
119    #endregion
120
121    private Thread scriptThread;
122    public virtual void Execute() {
123      if (compiledScript == null) return;
124      scriptThread = new Thread(() => {
125        Exception ex = null;
126        try {
127          OnScriptExecutionStarted();
128          compiledScript.Execute(VariableStore);
129        } catch (ThreadAbortException) {
130          // the execution was cancelled by the user
131        } catch (Exception e) {
132          ex = e;
133        } finally {
134          OnScriptExecutionFinished(ex);
135        }
136      });
137      scriptThread.Start();
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.