Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
04/08/14 23:28:40 (10 years ago)
Author:
abeham
Message:

#2136:

  • Split Script into Script and CSharpScript
  • Split ScriptView into ScriptView and CSharpScriptView
File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/sources/HeuristicLab.Scripting/3.3/Script.cs

    r10727 r10731  
    2929using System.Reflection;
    3030using System.Text;
    31 using System.Text.RegularExpressions;
    32 using System.Threading;
    3331using HeuristicLab.Common;
    3432using HeuristicLab.Common.Resources;
     
    3836
    3937namespace HeuristicLab.Scripting {
    40   [Item("C# Script", "An empty C# script.")]
    41   [Creatable("Scripts")]
    4238  [StorableClass]
    43   public sealed class Script : NamedItem, IStorableContent {
    44     #region Constants
    45     private const string ExecuteMethodName = "Execute";
    46     private const string CodeTemplate =
    47 @"// use 'vars' to access variables in the script's variable store (e.g. vars.x = 5)
    48 // use 'vars.Contains(string)' to check if a variable exists
    49 // use 'vars.Clear()' to remove all variables
    50 // use 'foreach (KeyValuePair<string, object> v in vars) { ... }' to iterate over all variables
    51 
    52 using System;
    53 using System.Linq;
    54 using System.Collections.Generic;
    55 using HeuristicLab.Common;
    56 using HeuristicLab.Core;
    57 using HeuristicLab.Data;
    58 
    59 public class UserScript : HeuristicLab.Scripting.UserScriptBase {
    60   public override void Main() {
    61     // type your code here
    62   }
    63 
    64   // implement further classes and methods
    65 
    66 }";
    67     #endregion
     39  public class Script : NamedItem {
     40    protected virtual string CodeTemplate {
     41      get { return string.Empty; }
     42    }
    6843
    6944    #region Fields & Properties
    70     private UserScriptBase compiledScript;
    71 
    72     public string Filename { get; set; }
    73 
    7445    public static new Image StaticItemImage {
    7546      get { return VSImageLibrary.Script; }
     
    7748
    7849    [Storable]
    79     private VariableStore variableStore;
    80     public VariableStore VariableStore {
    81       get { return variableStore; }
    82     }
    83 
    84     [Storable]
    8550    private string code;
    86     public string Code {
     51    public virtual string Code {
    8752      get { return code; }
    8853      set {
    8954        if (value == code) return;
    9055        code = value;
    91         compiledScript = null;
    9256        OnCodeChanged();
    9357      }
     
    9559
    9660    private string compilationUnitCode;
    97     public string CompilationUnitCode {
     61    public virtual string CompilationUnitCode {
    9862      get { return compilationUnitCode; }
    9963    }
    10064
    10165    private CompilerErrorCollection compileErrors;
    102     public CompilerErrorCollection CompileErrors {
     66    public virtual CompilerErrorCollection CompileErrors {
    10367      get { return compileErrors; }
    10468      private set {
     
    11175    #region Construction & Initialization
    11276    [StorableConstructor]
    113     private Script(bool deserializing) : base(deserializing) { }
    114     private Script(Script original, Cloner cloner)
     77    protected Script(bool deserializing) : base(deserializing) { }
     78    protected Script(Script original, Cloner cloner)
    11579      : base(original, cloner) {
    11680      code = original.code;
    117       variableStore = new VariableStore();
    11881      compilationUnitCode = original.compilationUnitCode;
    11982      if (original.compileErrors != null)
     
    12487      description = ItemDescription;
    12588      code = CodeTemplate;
    126       variableStore = new VariableStore();
    12789    }
    12890    public Script(string code)
     
    13698    #endregion
    13799
    138     private void RegisterScriptEvents() {
    139       if (compiledScript == null) return;
    140       compiledScript.ConsoleOutputChanged += compiledScript_ConsoleOutputChanged;
     100    #region Compilation
     101    protected virtual CSharpCodeProvider CodeProvider {
     102      get {
     103        return new CSharpCodeProvider(
     104          new Dictionary<string, string> {
     105                {"CompilerVersion", "v4.0"}, // support C# 4.0 syntax
     106              });
     107      }
    141108    }
    142109
    143     private void DeregisterScriptEvents() {
    144       if (compiledScript == null) return;
    145       compiledScript.ConsoleOutputChanged -= compiledScript_ConsoleOutputChanged;
    146     }
    147 
    148     #region Compilation
    149     private CSharpCodeProvider codeProvider =
    150       new CSharpCodeProvider(
    151         new Dictionary<string, string> {
    152           { "CompilerVersion", "v4.0" },  // support C# 4.0 syntax
    153         });
    154 
    155     private CompilerResults DoCompile() {
     110    protected virtual CompilerResults DoCompile() {
    156111      var parameters = new CompilerParameters {
    157112        GenerateExecutable = false,
     
    166121      var unit = CreateCompilationUnit();
    167122      var writer = new StringWriter();
    168       codeProvider.GenerateCodeFromCompileUnit(
     123      CodeProvider.GenerateCodeFromCompileUnit(
    169124        unit,
    170125        writer,
     
    174129        });
    175130      compilationUnitCode = writer.ToString();
    176       return codeProvider.CompileAssemblyFromDom(parameters, unit);
     131      return CodeProvider.CompileAssemblyFromDom(parameters, unit);
    177132    }
    178133
    179     public void Compile() {
     134    public virtual Assembly Compile() {
    180135      var results = DoCompile();
    181       compiledScript = null;
    182136      CompileErrors = results.Errors;
    183137      if (results.Errors.HasErrors) {
     
    188142            .AppendLine(error.ErrorText);
    189143        }
    190         throw new Exception(string.Format(
    191           "Compilation of \"{0}\" failed:{1}{2}",
    192           Name, Environment.NewLine,
    193           sb.ToString()));
     144        throw new Exception(string.Format("Compilation of \"{0}\" failed:{1}{2}",
     145          Name, Environment.NewLine, sb.ToString()));
    194146      } else {
    195         var assembly = results.CompiledAssembly;
    196         var types = assembly.GetTypes();
    197         DeregisterScriptEvents();
    198         compiledScript = (UserScriptBase)Activator.CreateInstance(types[0]);
    199         RegisterScriptEvents();
     147        return results.CompiledAssembly;
    200148      }
    201149    }
    202150
    203     public IEnumerable<Assembly> GetAssemblies() {
     151    public virtual IEnumerable<Assembly> GetAssemblies() {
    204152      var assemblies = new List<Assembly>();
    205153      foreach (var a in AppDomain.CurrentDomain.GetAssemblies()) {
     
    217165    }
    218166
    219     private readonly Regex SafeTypeNameCharRegex = new Regex("[_a-zA-Z0-9]+");
    220     private readonly Regex SafeTypeNameRegex = new Regex("[_a-zA-Z][_a-zA-Z0-9]*");
    221 
    222     private CodeCompileUnit CreateCompilationUnit() {
     167    protected virtual CodeCompileUnit CreateCompilationUnit() {
    223168      var unit = new CodeSnippetCompileUnit(code);
    224169      return unit;
    225170    }
    226 
    227     public string CompiledTypeName {
    228       get {
    229         var sb = new StringBuilder();
    230         var strings = SafeTypeNameCharRegex.Matches(Name)
    231                                            .Cast<Match>()
    232                                            .Select(m => m.Value);
    233         foreach (string s in strings)
    234           sb.Append(s);
    235         return SafeTypeNameRegex.Match(sb.ToString()).Value;
    236       }
    237     }
    238171    #endregion
    239172
    240     private Thread scriptThread;
    241     public void Execute() {
    242       if (compiledScript == null) return;
    243       var executeMethod = typeof(UserScriptBase).GetMethod(ExecuteMethodName, BindingFlags.NonPublic | BindingFlags.Instance);
    244       if (executeMethod != null) {
    245         scriptThread = new Thread(() => {
    246           Exception ex = null;
    247           try {
    248             OnScriptExecutionStarted();
    249             executeMethod.Invoke(compiledScript, new[] { VariableStore });
    250           } catch (ThreadAbortException) {
    251             // the execution was cancelled by the user
    252           } catch (TargetInvocationException e) {
    253             ex = e.InnerException;
    254           } finally {
    255             OnScriptExecutionFinished(ex);
    256           }
    257         });
    258         scriptThread.Start();
    259       }
    260     }
    261 
    262     public void Kill() {
    263       if (scriptThread.IsAlive)
    264         scriptThread.Abort();
    265     }
    266 
    267     private void compiledScript_ConsoleOutputChanged(object sender, EventArgs<string> e) {
    268       OnConsoleOutputChanged(e.Value);
    269     }
    270 
    271173    public event EventHandler CodeChanged;
    272     private void OnCodeChanged() {
     174    protected virtual void OnCodeChanged() {
    273175      var handler = CodeChanged;
    274176      if (handler != null) handler(this, EventArgs.Empty);
     
    276178
    277179    public event EventHandler CompileErrorsChanged;
    278     private void OnCompileErrorsChanged() {
     180    protected virtual void OnCompileErrorsChanged() {
    279181      var handler = CompileErrorsChanged;
    280182      if (handler != null) handler(this, EventArgs.Empty);
    281183    }
    282 
    283     public event EventHandler ScriptExecutionStarted;
    284     private void OnScriptExecutionStarted() {
    285       var handler = ScriptExecutionStarted;
    286       if (handler != null) handler(this, EventArgs.Empty);
    287     }
    288 
    289     public event EventHandler<EventArgs<Exception>> ScriptExecutionFinished;
    290     private void OnScriptExecutionFinished(Exception e) {
    291       var handler = ScriptExecutionFinished;
    292       if (handler != null) handler(this, new EventArgs<Exception>(e));
    293     }
    294 
    295     public event EventHandler<EventArgs<string>> ConsoleOutputChanged;
    296     private void OnConsoleOutputChanged(string args) {
    297       var handler = ConsoleOutputChanged;
    298       if (handler != null) handler(this, new EventArgs<string>(args));
    299     }
    300184  }
    301185}
Note: See TracChangeset for help on using the changeset viewer.