Free cookie consent management tool by TermsFeed Policy Generator

source: branches/OptimizationNetworks/HeuristicLab.Scripting/3.3/CSharpScript.cs @ 12229

Last change on this file since 12229 was 11576, checked in by swagner, 10 years ago

#2205: Merged changes r11062:11557 from trunk/sources into branches/OptimizationNetworks

File size: 5.5 KB
RevLine 
[10731]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)
[11576]40// use 'vars[string]' to access variables via runtime strings (e.g. vars[""x""] = 5)
[10731]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
[11576]44// use 'variables' to work with IEnumerable<T> extension methods on the script's variable store
[10731]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
[10857]66    private CSharpScriptBase compiledScript;
[10731]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) {
[11058]82      variableStore = cloner.Clone(original.variableStore);
[10731]83    }
84    public CSharpScript() {
85      variableStore = new VariableStore();
[10857]86      Code = CodeTemplate;
[10731]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() {
[10857]99      if (compiledScript != null)
100        compiledScript.ConsoleOutputChanged += CompiledScriptOnConsoleOutputChanged;
[10731]101    }
102
103    protected virtual void DeregisterScriptEvents() {
[10857]104      if (compiledScript != null)
105        compiledScript.ConsoleOutputChanged -= CompiledScriptOnConsoleOutputChanged;
[10731]106    }
107
108    #region Compilation
109
110    public override Assembly Compile() {
[10857]111      DeregisterScriptEvents();
112      compiledScript = null;
[10731]113      var assembly = base.Compile();
114      var types = assembly.GetTypes();
[10857]115      compiledScript = (CSharpScriptBase)Activator.CreateInstance(types.Single(x => typeof(CSharpScriptBase).IsAssignableFrom(x)));
[10731]116      RegisterScriptEvents();
117      return assembly;
118    }
119    #endregion
120
[10857]121    private Thread scriptThread;
[10731]122    public virtual void Execute() {
[10857]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      });
[11576]137      scriptThread.SetApartmentState(ApartmentState.STA);
[10857]138      scriptThread.Start();
[10731]139    }
140
141    public virtual void Kill() {
[10857]142      if (scriptThread.IsAlive)
143        scriptThread.Abort();
[10731]144    }
145
146    protected virtual void CompiledScriptOnConsoleOutputChanged(object sender, EventArgs<string> e) {
147      OnConsoleOutputChanged(e.Value);
148    }
149
150    public event EventHandler ScriptExecutionStarted;
151    protected virtual void OnScriptExecutionStarted() {
152      var handler = ScriptExecutionStarted;
153      if (handler != null) handler(this, EventArgs.Empty);
154    }
155
156    public event EventHandler<EventArgs<Exception>> ScriptExecutionFinished;
157    protected virtual void OnScriptExecutionFinished(Exception e) {
158      var handler = ScriptExecutionFinished;
159      if (handler != null) handler(this, new EventArgs<Exception>(e));
160    }
161
162    public event EventHandler<EventArgs<string>> ConsoleOutputChanged;
163    protected virtual void OnConsoleOutputChanged(string args) {
164      var handler = ConsoleOutputChanged;
165      if (handler != null) handler(this, new EventArgs<string>(args));
166    }
167  }
168}
Note: See TracBrowser for help on using the repository browser.