Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
05/26/14 16:41:12 (10 years ago)
Author:
abeham
Message:

#2136: merged r10510, r10511, r10512, r10566, r10577, r10642, r10727, r10731, r10747, r10761, r10857, r10865 to stable

Location:
stable
Files:
2 edited
1 copied

Legend:

Unmodified
Added
Removed
  • stable

  • stable/HeuristicLab.Scripting/3.3/Script.cs

    r10506 r10892  
    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("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 global variables in the variable store
    48 
    49 using System;
    50 using System.Linq;
    51 using System.Collections.Generic;
    52 using HeuristicLab.Common;
    53 using HeuristicLab.Core;
    54 using HeuristicLab.Data;
    55 
    56 public class UserScript : HeuristicLab.Scripting.UserScriptBase {
    57   public override void Main() {
    58     // type your code here
    59   }
    60 
    61   // further classes and methods
    62 
    63 }";
    64     #endregion
     39  public class Script : NamedItem {
     40    protected virtual string CodeTemplate {
     41      get { return string.Empty; }
     42    }
    6543
    6644    #region Fields & Properties
    67     private UserScriptBase compiledScript;
    68 
    69     public string Filename { get; set; }
    70 
    7145    public static new Image StaticItemImage {
    7246      get { return VSImageLibrary.Script; }
    73     }
    74 
    75     [Storable]
    76     private VariableStore variableStore;
    77     public VariableStore VariableStore {
    78       get { return variableStore; }
    7947    }
    8048
     
    8654        if (value == code) return;
    8755        code = value;
    88         compiledScript = null;
    8956        OnCodeChanged();
    9057      }
    91     }
    92 
    93     private string compilationUnitCode;
    94     public string CompilationUnitCode {
    95       get { return compilationUnitCode; }
    9658    }
    9759
     
    10870    #region Construction & Initialization
    10971    [StorableConstructor]
    110     private Script(bool deserializing) : base(deserializing) { }
    111     private Script(Script original, Cloner cloner)
     72    protected Script(bool deserializing) : base(deserializing) { }
     73    protected Script(Script original, Cloner cloner)
    11274      : base(original, cloner) {
    11375      code = original.code;
    114       variableStore = new VariableStore();
    115       compilationUnitCode = original.compilationUnitCode;
    11676      if (original.compileErrors != null)
    11777        compileErrors = new CompilerErrorCollection(original.compileErrors);
    11878    }
    119 
    12079    public Script()
    121       : base("Script", "A HeuristicLab script.") {
    122       code = CodeTemplate;
    123       variableStore = new VariableStore();
     80      : base("Script", "An empty script.") {
     81      code = string.Empty;
     82    }
     83    public Script(string code)
     84      : this() {
     85      this.code = code;
    12486    }
    12587
     
    12991    #endregion
    13092
    131     private void RegisterScriptEvents() {
    132       if (compiledScript == null) return;
    133       compiledScript.ConsoleOutputChanged += compiledScript_ConsoleOutputChanged;
     93    #region Compilation
     94    protected virtual CSharpCodeProvider CodeProvider {
     95      get {
     96        return new CSharpCodeProvider(
     97          new Dictionary<string, string> {
     98                {"CompilerVersion", "v4.0"}, // support C# 4.0 syntax
     99              });
     100      }
    134101    }
    135102
    136     private void DeregisterScriptEvents() {
    137       if (compiledScript == null) return;
    138       compiledScript.ConsoleOutputChanged -= compiledScript_ConsoleOutputChanged;
    139     }
    140 
    141     #region Compilation
    142     private CSharpCodeProvider codeProvider =
    143       new CSharpCodeProvider(
    144         new Dictionary<string, string> {
    145           { "CompilerVersion", "v4.0" },  // support C# 4.0 syntax
    146         });
    147 
    148     private CompilerResults DoCompile() {
     103    protected virtual CompilerResults DoCompile() {
    149104      var parameters = new CompilerParameters {
    150105        GenerateExecutable = false,
     
    159114      var unit = CreateCompilationUnit();
    160115      var writer = new StringWriter();
    161       codeProvider.GenerateCodeFromCompileUnit(
     116      CodeProvider.GenerateCodeFromCompileUnit(
    162117        unit,
    163118        writer,
     
    166121          IndentString = "  ",
    167122        });
    168       compilationUnitCode = writer.ToString();
    169       return codeProvider.CompileAssemblyFromDom(parameters, unit);
     123      return CodeProvider.CompileAssemblyFromDom(parameters, unit);
    170124    }
    171125
    172     public void Compile() {
     126    public virtual Assembly Compile() {
    173127      var results = DoCompile();
    174       compiledScript = null;
    175128      CompileErrors = results.Errors;
    176129      if (results.Errors.HasErrors) {
     
    181134            .AppendLine(error.ErrorText);
    182135        }
    183         throw new Exception(string.Format(
    184           "Compilation of \"{0}\" failed:{1}{2}",
    185           Name, Environment.NewLine,
    186           sb.ToString()));
     136        throw new Exception(string.Format("Compilation of \"{0}\" failed:{1}{2}",
     137          Name, Environment.NewLine, sb.ToString()));
    187138      } else {
    188         var assembly = results.CompiledAssembly;
    189         var types = assembly.GetTypes();
    190         DeregisterScriptEvents();
    191         compiledScript = (UserScriptBase)Activator.CreateInstance(types[0]);
    192         RegisterScriptEvents();
     139        return results.CompiledAssembly;
    193140      }
    194141    }
    195142
    196     public IEnumerable<Assembly> GetAssemblies() {
     143    public virtual IEnumerable<Assembly> GetAssemblies() {
    197144      var assemblies = new List<Assembly>();
    198145      foreach (var a in AppDomain.CurrentDomain.GetAssemblies()) {
     
    210157    }
    211158
    212     private readonly Regex SafeTypeNameCharRegex = new Regex("[_a-zA-Z0-9]+");
    213     private readonly Regex SafeTypeNameRegex = new Regex("[_a-zA-Z][_a-zA-Z0-9]*");
    214 
    215     private CodeCompileUnit CreateCompilationUnit() {
     159    protected virtual CodeCompileUnit CreateCompilationUnit() {
    216160      var unit = new CodeSnippetCompileUnit(code);
    217161      return unit;
    218162    }
    219 
    220     public string CompiledTypeName {
    221       get {
    222         var sb = new StringBuilder();
    223         var strings = SafeTypeNameCharRegex.Matches(Name)
    224                                            .Cast<Match>()
    225                                            .Select(m => m.Value);
    226         foreach (string s in strings)
    227           sb.Append(s);
    228         return SafeTypeNameRegex.Match(sb.ToString()).Value;
    229       }
    230     }
    231163    #endregion
    232164
    233     private Thread scriptThread;
    234     public void Execute() {
    235       if (compiledScript == null) return;
    236       var executeMethod = typeof(UserScriptBase).GetMethod(ExecuteMethodName, BindingFlags.NonPublic | BindingFlags.Instance);
    237       if (executeMethod != null) {
    238         scriptThread = new Thread(() => {
    239           Exception ex = null;
    240           try {
    241             OnScriptExecutionStarted();
    242             executeMethod.Invoke(compiledScript, new[] { VariableStore });
    243           } catch (ThreadAbortException) {
    244             // the execution was cancelled by the user
    245           } catch (TargetInvocationException e) {
    246             ex = e.InnerException;
    247           } finally {
    248             OnScriptExecutionFinished(ex);
    249           }
    250         });
    251         scriptThread.Start();
    252       }
    253     }
    254 
    255     public void Kill() {
    256       if (scriptThread.IsAlive)
    257         scriptThread.Abort();
    258     }
    259 
    260     private void compiledScript_ConsoleOutputChanged(object sender, EventArgs<string> e) {
    261       OnConsoleOutputChanged(e.Value);
    262     }
    263 
    264165    public event EventHandler CodeChanged;
    265     private void OnCodeChanged() {
     166    protected virtual void OnCodeChanged() {
    266167      var handler = CodeChanged;
    267168      if (handler != null) handler(this, EventArgs.Empty);
     
    269170
    270171    public event EventHandler CompileErrorsChanged;
    271     private void OnCompileErrorsChanged() {
     172    protected virtual void OnCompileErrorsChanged() {
    272173      var handler = CompileErrorsChanged;
    273174      if (handler != null) handler(this, EventArgs.Empty);
    274175    }
    275 
    276     public event EventHandler ScriptExecutionStarted;
    277     private void OnScriptExecutionStarted() {
    278       var handler = ScriptExecutionStarted;
    279       if (handler != null) handler(this, EventArgs.Empty);
    280     }
    281 
    282     public event EventHandler<EventArgs<Exception>> ScriptExecutionFinished;
    283     private void OnScriptExecutionFinished(Exception e) {
    284       var handler = ScriptExecutionFinished;
    285       if (handler != null) handler(this, new EventArgs<Exception>(e));
    286     }
    287 
    288     public event EventHandler<EventArgs<string>> ConsoleOutputChanged;
    289     private void OnConsoleOutputChanged(string args) {
    290       var handler = ConsoleOutputChanged;
    291       if (handler != null) handler(this, new EventArgs<string>(args));
    292     }
    293176  }
    294177}
Note: See TracChangeset for help on using the changeset viewer.