Free cookie consent management tool by TermsFeed Policy Generator

Changeset 2660


Ignore:
Timestamp:
01/20/10 16:16:02 (15 years ago)
Author:
epitzer
Message:

New ProgrammableOperator with syntax highlighting, code completion, configurable assemblies and namespaces (#842)

Location:
trunk/sources
Files:
9 edited

Legend:

Unmodified
Added
Removed
  • trunk/sources/HeuristicLab 3.2.sln

    r2657 r2660  
    322322EndProject
    323323Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HeuristicLab.SQLServerCompact-3.5.5692.0", "HeuristicLab.ExtLibs\HeuristicLab.SQLServerCompact\3.5.5692.0\HeuristicLab.SQLServerCompact-3.5.5692.0.csproj", "{31DD6385-7276-49ED-9533-823D4CDF3D2A}"
     324EndProject
     325Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "HeuristicLab.SharpDevelop", "HeuristicLab.SharpDevelop", "{92CB7C8C-0175-44E9-B7A6-73BFC5392D79}"
     326EndProject
     327Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HeuristicLab.SharpDevelop-3.1.1.5327", "HeuristicLab.ExtLibs\HeuristicLab.SharpDevelop\3.1.1.5327\HeuristicLab.SharpDevelop-3.1.1.5327.csproj", "{4ABA047D-46DD-4608-9E4A-41C5F92FDBB1}"
     328EndProject
     329Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "3.1.1.5327", "3.1.1.5327", "{6C60D339-4ED0-488D-BE7B-BFAC7DAA9701}"
     330EndProject
     331Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HeuristicLab.CodeEditor-3.2", "HeuristicLab.CodeEditor\3.2\HeuristicLab.CodeEditor-3.2.csproj", "{489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}"
    324332EndProject
    325333Global
     
    27022710    {31DD6385-7276-49ED-9533-823D4CDF3D2A}.Release|x86.ActiveCfg = Release|x86
    27032711    {31DD6385-7276-49ED-9533-823D4CDF3D2A}.Release|x86.Build.0 = Release|x86
     2712    {4ABA047D-46DD-4608-9E4A-41C5F92FDBB1}.CEDMA Debug|Any CPU.ActiveCfg = Debug|Any CPU
     2713    {4ABA047D-46DD-4608-9E4A-41C5F92FDBB1}.CEDMA Debug|Any CPU.Build.0 = Debug|Any CPU
     2714    {4ABA047D-46DD-4608-9E4A-41C5F92FDBB1}.CEDMA Debug|x64.ActiveCfg = Debug|x64
     2715    {4ABA047D-46DD-4608-9E4A-41C5F92FDBB1}.CEDMA Debug|x64.Build.0 = Debug|x64
     2716    {4ABA047D-46DD-4608-9E4A-41C5F92FDBB1}.CEDMA Debug|x86.ActiveCfg = Debug|x86
     2717    {4ABA047D-46DD-4608-9E4A-41C5F92FDBB1}.CEDMA Debug|x86.Build.0 = Debug|x86
     2718    {4ABA047D-46DD-4608-9E4A-41C5F92FDBB1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
     2719    {4ABA047D-46DD-4608-9E4A-41C5F92FDBB1}.Debug|Any CPU.Build.0 = Debug|Any CPU
     2720    {4ABA047D-46DD-4608-9E4A-41C5F92FDBB1}.Debug|x64.ActiveCfg = Debug|x64
     2721    {4ABA047D-46DD-4608-9E4A-41C5F92FDBB1}.Debug|x64.Build.0 = Debug|x64
     2722    {4ABA047D-46DD-4608-9E4A-41C5F92FDBB1}.Debug|x86.ActiveCfg = Debug|x86
     2723    {4ABA047D-46DD-4608-9E4A-41C5F92FDBB1}.Debug|x86.Build.0 = Debug|x86
     2724    {4ABA047D-46DD-4608-9E4A-41C5F92FDBB1}.Modeling Debug|Any CPU.ActiveCfg = Debug|Any CPU
     2725    {4ABA047D-46DD-4608-9E4A-41C5F92FDBB1}.Modeling Debug|Any CPU.Build.0 = Debug|Any CPU
     2726    {4ABA047D-46DD-4608-9E4A-41C5F92FDBB1}.Modeling Debug|x64.ActiveCfg = Debug|x64
     2727    {4ABA047D-46DD-4608-9E4A-41C5F92FDBB1}.Modeling Debug|x64.Build.0 = Debug|x64
     2728    {4ABA047D-46DD-4608-9E4A-41C5F92FDBB1}.Modeling Debug|x86.ActiveCfg = Debug|x86
     2729    {4ABA047D-46DD-4608-9E4A-41C5F92FDBB1}.Modeling Debug|x86.Build.0 = Debug|x86
     2730    {4ABA047D-46DD-4608-9E4A-41C5F92FDBB1}.Release|Any CPU.ActiveCfg = Release|Any CPU
     2731    {4ABA047D-46DD-4608-9E4A-41C5F92FDBB1}.Release|Any CPU.Build.0 = Release|Any CPU
     2732    {4ABA047D-46DD-4608-9E4A-41C5F92FDBB1}.Release|x64.ActiveCfg = Release|x64
     2733    {4ABA047D-46DD-4608-9E4A-41C5F92FDBB1}.Release|x64.Build.0 = Release|x64
     2734    {4ABA047D-46DD-4608-9E4A-41C5F92FDBB1}.Release|x86.ActiveCfg = Release|x86
     2735    {4ABA047D-46DD-4608-9E4A-41C5F92FDBB1}.Release|x86.Build.0 = Release|x86
     2736    {489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}.CEDMA Debug|Any CPU.ActiveCfg = Debug|Any CPU
     2737    {489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}.CEDMA Debug|Any CPU.Build.0 = Debug|Any CPU
     2738    {489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}.CEDMA Debug|x64.ActiveCfg = Debug|x86
     2739    {489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}.CEDMA Debug|x86.ActiveCfg = Debug|x86
     2740    {489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}.CEDMA Debug|x86.Build.0 = Debug|x86
     2741    {489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
     2742    {489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}.Debug|Any CPU.Build.0 = Debug|Any CPU
     2743    {489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}.Debug|x64.ActiveCfg = Debug|x64
     2744    {489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}.Debug|x64.Build.0 = Debug|x64
     2745    {489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}.Debug|x86.ActiveCfg = Debug|x86
     2746    {489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}.Debug|x86.Build.0 = Debug|x86
     2747    {489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}.Modeling Debug|Any CPU.ActiveCfg = Debug|Any CPU
     2748    {489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}.Modeling Debug|Any CPU.Build.0 = Debug|Any CPU
     2749    {489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}.Modeling Debug|x64.ActiveCfg = Debug|x86
     2750    {489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}.Modeling Debug|x86.ActiveCfg = Debug|x86
     2751    {489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}.Modeling Debug|x86.Build.0 = Debug|x86
     2752    {489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}.Release|Any CPU.ActiveCfg = Release|Any CPU
     2753    {489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}.Release|Any CPU.Build.0 = Release|Any CPU
     2754    {489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}.Release|x64.ActiveCfg = Release|x64
     2755    {489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}.Release|x64.Build.0 = Release|x64
     2756    {489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}.Release|x86.ActiveCfg = Release|x86
     2757    {489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}.Release|x86.Build.0 = Release|x86
    27042758  EndGlobalSection
    27052759  GlobalSection(SolutionProperties) = preSolution
     
    27082762  GlobalSection(NestedProjects) = preSolution
    27092763    {D04A93C2-6903-4DCA-8803-2EBF60975E47} = {A0AEB817-CAC7-4DC8-8D39-0E040BA027E5}
    2710     {C2614CCD-A8B9-4BA2-86DA-6584CAA0087C} = {A0AEB817-CAC7-4DC8-8D39-0E040BA027E5}
    27112764    {BC9B1349-F788-4293-AA27-0B3474761C7F} = {A0AEB817-CAC7-4DC8-8D39-0E040BA027E5}
    27122765    {9CAC84CA-BEB1-44F9-95E7-75ACEFF98693} = {A0AEB817-CAC7-4DC8-8D39-0E040BA027E5}
    27132766    {66A6D1DA-E53C-455D-9F53-07C0128CBF29} = {A0AEB817-CAC7-4DC8-8D39-0E040BA027E5}
    27142767    {823E15D8-30DC-4D69-804B-53BDF8D70E39} = {A0AEB817-CAC7-4DC8-8D39-0E040BA027E5}
     2768    {C2614CCD-A8B9-4BA2-86DA-6584CAA0087C} = {A0AEB817-CAC7-4DC8-8D39-0E040BA027E5}
     2769    {92CB7C8C-0175-44E9-B7A6-73BFC5392D79} = {A0AEB817-CAC7-4DC8-8D39-0E040BA027E5}
    27152770    {DD1A12A4-88DE-4991-8CBC-9AC2E57EADC3} = {D04A93C2-6903-4DCA-8803-2EBF60975E47}
    2716     {31DD6385-7276-49ED-9533-823D4CDF3D2A} = {C2614CCD-A8B9-4BA2-86DA-6584CAA0087C}
    27172771    {678E2145-8152-4E19-9646-07D439D00301} = {DD1A12A4-88DE-4991-8CBC-9AC2E57EADC3}
    27182772    {1849A92E-DCFC-4E05-BB0A-D7B7A3DAFCFB} = {DD1A12A4-88DE-4991-8CBC-9AC2E57EADC3}
     
    27252779    {89B50302-9CEE-4D13-9779-633EADCAE624} = {FDB65084-1E00-4BCF-90A7-C69BBEC014F8}
    27262780    {1B3063DB-D71C-4A6A-A359-883E8F53A140} = {823E15D8-30DC-4D69-804B-53BDF8D70E39}
     2781    {31DD6385-7276-49ED-9533-823D4CDF3D2A} = {C2614CCD-A8B9-4BA2-86DA-6584CAA0087C}
     2782    {6C60D339-4ED0-488D-BE7B-BFAC7DAA9701} = {92CB7C8C-0175-44E9-B7A6-73BFC5392D79}
     2783    {4ABA047D-46DD-4608-9E4A-41C5F92FDBB1} = {6C60D339-4ED0-488D-BE7B-BFAC7DAA9701}
    27272784  EndGlobalSection
    27282785EndGlobal
  • trunk/sources/HeuristicLab.CodeEditor/3.2/HeuristicLab.CodeEditor-3.2.csproj

    r2659 r2660  
    5656    <DebugType>None</DebugType>
    5757    <PlatformTarget>x86</PlatformTarget>
     58  </PropertyGroup>
     59  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' ">
     60    <DebugSymbols>true</DebugSymbols>
     61    <OutputPath>bin\x64\Debug\</OutputPath>
     62    <DefineConstants>DEBUG;TRACE</DefineConstants>
     63    <CheckForOverflowUnderflow>true</CheckForOverflowUnderflow>
     64    <FileAlignment>4096</FileAlignment>
     65    <DebugType>Full</DebugType>
     66    <PlatformTarget>x64</PlatformTarget>
     67  </PropertyGroup>
     68  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x64' ">
     69    <OutputPath>bin\x64\Release\</OutputPath>
     70    <DefineConstants>TRACE</DefineConstants>
     71    <Optimize>true</Optimize>
     72    <FileAlignment>4096</FileAlignment>
     73    <DebugType>None</DebugType>
     74    <PlatformTarget>x64</PlatformTarget>
    5875  </PropertyGroup>
    5976  <ItemGroup>
  • trunk/sources/HeuristicLab.Operators.Programmable/3.2/HeuristicLab.Operators.Programmable-3.2.csproj

    r1534 r2660  
    100100  </ItemGroup>
    101101  <ItemGroup>
     102    <ProjectReference Include="..\..\HeuristicLab.CodeEditor\3.2\HeuristicLab.CodeEditor-3.2.csproj">
     103      <Project>{489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}</Project>
     104      <Name>HeuristicLab.CodeEditor-3.2</Name>
     105    </ProjectReference>
    102106    <ProjectReference Include="..\..\HeuristicLab.Core\3.2\HeuristicLab.Core-3.2.csproj">
    103107      <Project>{F43B59AB-2B8C-4570-BC1E-15592086517C}</Project>
  • trunk/sources/HeuristicLab.Operators.Programmable/3.2/HeuristicLabOperatorsProgrammablePlugin.cs

    r2591 r2660  
    3131  [PluginDependency("HeuristicLab.Data-3.2")]
    3232  [PluginDependency("HeuristicLab.Operators-3.2")]
     33  [PluginDependency("HeuristicLab.CodeEditor-3.2")]
    3334  public class HeuristicLabOperatorsProgrammablePlugin : PluginBase {
    3435  }
  • trunk/sources/HeuristicLab.Operators.Programmable/3.2/ProgrammableOperator.cs

    r2533 r2660  
    3434using HeuristicLab.Data;
    3535using System.Data.Linq;
     36using System.Xml.XPath;
    3637
    3738namespace HeuristicLab.Operators.Programmable {
     39
    3840  public class ProgrammableOperator : OperatorBase {
     41
     42    #region Fields & Properties
     43
    3944    private MethodInfo executeMethod;
    40 
    41     private string myDescription;
     45    public CompilerErrorCollection CompileErrors { get; private set; }
     46    public string CompilationUnitCode { get; private set; }
     47
     48    private string description;
    4249    public override string Description {
    43       get { return myDescription; }
    44     }
    45     private string myCode;
     50      get { return description; }
     51    }
     52
     53    private string code;
    4654    public string Code {
    47       get { return myCode; }
     55      get { return code; }
    4856      set {
    49         if (value != myCode) {
    50           myCode = value;
     57        if (value != code) {
     58          code = value;
    5159          executeMethod = null;
    5260          OnCodeChanged();
     
    5765    private object syncRoot = new object();
    5866
    59     public ProgrammableOperator() {
    60       myCode = "Result.Data = true;";
    61       myDescription = "An operator that can be programmed for arbitrary needs.";
    62       AddVariableInfo(new VariableInfo("Result", "A computed variable", typeof(BoolData), VariableKind.New | VariableKind.Out));
    63       executeMethod = null;
     67    protected Dictionary<Assembly, bool> Assemblies;
     68    public IEnumerable<Assembly> AvailableAssemblies {
     69      get { return Assemblies.Keys; }
     70    }
     71
     72    public IEnumerable<Assembly> SelectedAssemblies {
     73      get { return Assemblies.Where(kvp => kvp.Value).Select(kvp => kvp.Key); }
     74    }
     75
     76    private HashSet<string> namespaces;
     77    public IEnumerable<string> Namespaces {
     78      get { return namespaces; }
     79    }
     80
     81    #endregion
     82
     83    #region Extended Accessors
     84
     85    public void SelectAssembly(Assembly a) {
     86      Assemblies[a] = true;
     87    }
     88
     89    public void UnselectAssembly(Assembly a) {
     90      Assemblies[a] = false;
     91    }
     92
     93    public void SelectNamespace(string ns) {
     94      namespaces.Add(ns);
     95    }
     96
     97    public void UnselectNamespace(string ns) {
     98      namespaces.Remove(ns);
    6499    }
    65100
     
    68103        throw new NullReferenceException("description must not be null");
    69104
    70       if (description != myDescription) {
    71         myDescription = description;
     105      if (description != this.description) {
     106        this.description = description;
    72107        OnDescriptionChanged();
    73108      }
    74109    }
    75110
     111    public IEnumerable<string> GetAllNamespaces(bool selectedAssembliesOnly) {
     112      var namespaces = new HashSet<string>();
     113      foreach (var a in Assemblies) {
     114        if (!selectedAssembliesOnly || a.Value) {
     115          foreach (var t in a.Key.GetTypes()) {
     116            if (t.IsPublic) {
     117              namespaces.Add(t.Namespace);
     118            }
     119          }
     120        }
     121      }
     122      return namespaces;
     123    }
     124    #endregion
     125
     126    #region Construction & Initialization
     127
     128    public ProgrammableOperator() {
     129      code = "";
     130      description = "An operator that can be programmed for arbitrary needs.";
     131      executeMethod = null;
     132      Assemblies = DiscoverAssemblies();
     133      namespaces = new HashSet<string>(DiscoverNamespaces());
     134    }
     135
     136    protected static List<Assembly> defaultAssemblies = new List<Assembly>() {     
     137      typeof(System.Linq.Enumerable).Assembly,  // add reference to version 3.5 of System.dll
     138      typeof(System.Collections.Generic.List<>).Assembly,
     139      typeof(System.Text.StringBuilder).Assembly,     
     140      typeof(System.Data.Linq.DataContext).Assembly,
     141      typeof(HeuristicLab.Core.OperatorBase).Assembly,
     142      typeof(HeuristicLab.Data.IntData).Assembly,     
     143     
     144    };
     145
     146    protected static Dictionary<Assembly, bool> DiscoverAssemblies() {
     147      var assemblies = new Dictionary<Assembly, bool>();
     148      foreach (var a in AppDomain.CurrentDomain.GetAssemblies()) {
     149        try {
     150          string location = a.Location;
     151          assemblies.Add(a, false);
     152        } catch (NotSupportedException) {
     153          // NotSupportedException is thrown while accessing
     154          // the Location property of the anonymously hosted
     155          // dynamic methods assembly, which is related to
     156          // LINQ queries
     157        }
     158      }
     159      foreach (var a in defaultAssemblies) {
     160        if (assemblies.ContainsKey(a)) {
     161          assemblies[a] = true;
     162        } else {
     163          assemblies.Add(a, true);
     164        }
     165      }
     166      return assemblies;
     167    }
     168
     169    protected static List<string> DiscoverNamespaces() {
     170      return new List<string>() {
     171        "System",
     172        "System.Collections.Generic",
     173        "System.Text",
     174        "System.Linq",
     175        "System.Data.Linq",
     176        "HeuristicLab.Core",
     177        "HeuristicLab.Data",
     178      };
     179    }
     180
     181    #endregion
     182
     183    #region Compilation
     184
     185    private static CSharpCodeProvider codeProvider =
     186      new CSharpCodeProvider(
     187        new Dictionary<string, string>() {
     188          { "CompilerVersion", "v3.5" },  // support C# 3.0 syntax
     189        });
     190
     191    private CompilerResults DoCompile() {
     192      CompilerParameters parameters = new CompilerParameters();
     193      parameters.GenerateExecutable = false;
     194      parameters.GenerateInMemory = true;
     195      parameters.IncludeDebugInformation = false;
     196      parameters.ReferencedAssemblies.AddRange(SelectedAssemblies.Select(a => a.Location).ToArray());
     197      var unit = CreateCompilationUnit();
     198      var writer = new StringWriter();
     199      codeProvider.GenerateCodeFromCompileUnit(
     200        unit,
     201        writer,
     202        new CodeGeneratorOptions() {
     203          BracingStyle = "C",
     204          ElseOnClosing = true,
     205          IndentString = "  ",
     206        });
     207      CompilationUnitCode = writer.ToString();
     208      return codeProvider.CompileAssemblyFromDom(parameters, unit);
     209    }
     210
    76211    public virtual void Compile() {
     212      var results = DoCompile();
     213      executeMethod = null;
     214      if (results.Errors.HasErrors) {
     215        CompileErrors = results.Errors;
     216        StringBuilder sb = new StringBuilder();
     217        foreach (CompilerError error in results.Errors) {
     218          sb.Append(error.Line).Append(':')
     219            .Append(error.Column).Append(": ")
     220            .AppendLine(error.ErrorText);
     221        }
     222        throw new Exception(string.Format(
     223          "Compilation of \"{0}\" failed:{1}{2}",
     224          Name, Environment.NewLine,
     225          sb.ToString()));
     226      } else {
     227        CompileErrors = null;
     228        Assembly assembly = results.CompiledAssembly;
     229        Type[] types = assembly.GetTypes();
     230        executeMethod = types[0].GetMethod("Execute");
     231      }
     232    }
     233
     234    private CodeCompileUnit CreateCompilationUnit() {
    77235      CodeNamespace ns = new CodeNamespace("HeuristicLab.Operators.Programmable.CustomOperators");
    78       CodeTypeDeclaration typeDecl = new CodeTypeDeclaration("Operator");
    79       typeDecl.IsClass = true;
    80       typeDecl.TypeAttributes = TypeAttributes.Public;
    81 
     236      ns.Types.Add(CreateType());
     237      ns.Imports.AddRange(
     238        GetSelectedAndValidNamespaces()
     239        .Select(n => new CodeNamespaceImport(n))
     240        .ToArray());
     241      CodeCompileUnit unit = new CodeCompileUnit();
     242      unit.Namespaces.Add(ns);
     243      return unit;
     244    }
     245
     246    public IEnumerable<string> GetSelectedAndValidNamespaces() {
     247      var possibleNamespaces = new HashSet<string>(GetAllNamespaces(true));
     248      foreach (var ns in Namespaces)
     249        if (possibleNamespaces.Contains(ns))
     250          yield return ns;     
     251    }
     252
     253    public static readonly Regex SafeTypeNameCharRegex = new Regex("[_a-zA-Z0-9]+");
     254    public static readonly Regex SafeTypeNameRegex = new Regex("[_a-zA-Z][_a-zA-Z0-9]*");
     255
     256    public string CompiledTypeName {
     257      get {
     258        var sb = new StringBuilder();
     259        foreach (string s in SafeTypeNameCharRegex.Matches(Name).Cast<Match>().Select(m => m.Value)) {
     260          sb.Append(s);
     261        }
     262        return SafeTypeNameRegex.Match(sb.ToString()).Value;
     263      }
     264    }
     265
     266    private CodeTypeDeclaration CreateType() {
     267      CodeTypeDeclaration typeDecl = new CodeTypeDeclaration(CompiledTypeName) {
     268        IsClass = true,
     269        TypeAttributes = TypeAttributes.Public,
     270      };
     271      typeDecl.Members.Add(CreateMethod());
     272      return typeDecl;
     273    }
     274
     275    public string Signature {
     276      get {
     277        var sb = new StringBuilder()
     278        .Append("public static IOperation Execute(IOperator op, IScope scope");
     279        foreach (var info in VariableInfos)
     280          sb.Append(String.Format(", {0} {1}", info.DataType.Name, info.FormalName));
     281        return sb.Append(")").ToString();
     282      }
     283    }
     284
     285    private static Regex lineSplitter = new Regex(@"\r\n|\r|\n");
     286
     287    private CodeMemberMethod CreateMethod() {
    82288      CodeMemberMethod method = new CodeMemberMethod();
    83289      method.Name = "Execute";
    84       method.ReturnType = new CodeTypeReference(typeof(IOperation));
     290      method.ReturnType = new CodeTypeReference(typeof(HeuristicLab.Core.IOperation));
    85291      method.Attributes = MemberAttributes.Public | MemberAttributes.Static;
    86292      method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(IOperator), "op"));
     
    88294      foreach (IVariableInfo info in VariableInfos)
    89295        method.Parameters.Add(new CodeParameterDeclarationExpression(info.DataType, info.FormalName));
    90       string code = myCode + "\r\n" + "return null;";
    91       method.Statements.Add(new CodeSnippetStatement(code));
    92       typeDecl.Members.Add(method);
    93 
    94       ns.Types.Add(typeDecl);
    95       ns.Imports.Add(new CodeNamespaceImport("System"));
    96       ns.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
    97       ns.Imports.Add(new CodeNamespaceImport("System.Text"));
    98       ns.Imports.Add(new CodeNamespaceImport("System.Linq"));
    99       ns.Imports.Add(new CodeNamespaceImport("System.Data.Linq"));
    100       ns.Imports.Add(new CodeNamespaceImport("HeuristicLab.Core"));
    101       foreach (IVariableInfo variableInfo in VariableInfos)
    102         ns.Imports.Add(new CodeNamespaceImport(variableInfo.DataType.Namespace));
    103 
    104       CodeCompileUnit unit = new CodeCompileUnit();
    105       unit.Namespaces.Add(ns);
    106       CompilerParameters parameters = new CompilerParameters();
    107       parameters.GenerateExecutable = false;
    108       parameters.GenerateInMemory = true;
    109       parameters.IncludeDebugInformation = false;
    110       Assembly[] loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
    111       foreach (Assembly loadedAssembly in loadedAssemblies) {
    112         try {
    113           parameters.ReferencedAssemblies.Add(loadedAssembly.Location);
    114         }
    115         catch (NotSupportedException) {
    116           //NotSupportedException is thrown while accessing the Location property of the anonymously hosted dynamic methods assembly,
    117           //which is related to LINQ queries
    118         }
    119       }
    120       parameters.ReferencedAssemblies.Add(typeof(Enumerable).Assembly.Location); // add reference to version 3.5 of System.dll
    121       parameters.ReferencedAssemblies.Add(typeof(DataContext).Assembly.Location); // add reference System.Data.Linq.Dll
    122       CodeDomProvider provider = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });  // support C# 3.0 syntax
    123       CompilerResults results = provider.CompileAssemblyFromDom(parameters, unit);
    124 
    125       executeMethod = null;
    126       if (results.Errors.HasErrors) {
    127         StringWriter writer = new StringWriter();
    128         CodeGeneratorOptions options = new CodeGeneratorOptions();
    129         options.BlankLinesBetweenMembers = false;
    130         options.ElseOnClosing = true;
    131         options.IndentString = "  ";
    132         provider.GenerateCodeFromCompileUnit(unit, writer, options);
    133         writer.Flush();
    134         string[] source = writer.ToString().Split(new string[] { "\r\n" }, StringSplitOptions.None);
    135         StringBuilder builder = new StringBuilder();
    136         for (int i = 0; i < source.Length; i++)
    137           builder.AppendLine((i + 3).ToString("###") + "     " + source[i]);
    138         builder.AppendLine();
    139         builder.AppendLine();
    140         builder.AppendLine();
    141         foreach (CompilerError error in results.Errors) {
    142           builder.Append("Line " + error.Line.ToString());
    143           builder.Append(", Column " + error.Column.ToString());
    144           builder.AppendLine(": " + error.ErrorText);
    145         }
    146         throw new Exception("Compile Errors:\n\n" + builder.ToString());
    147       } else {
    148         Assembly assembly = results.CompiledAssembly;
    149         Type[] types = assembly.GetTypes();
    150         executeMethod = types[0].GetMethod("Execute");
    151       }
    152     }
    153 
    154     public override object Clone(IDictionary<Guid, object> clonedObjects) {
    155       ProgrammableOperator clone = (ProgrammableOperator)base.Clone(clonedObjects);
    156       clone.myDescription = Description;
    157       clone.myCode = Code;
    158       clone.executeMethod = executeMethod;
    159       return clone;
    160     }
     296      string[] codeLines = lineSplitter.Split(code);
     297      for (int i = 0; i < codeLines.Length; i++) {
     298        codeLines[i] = string.Format("#line {0} \"ProgrammableOperator\"{1}{2}", i + 1, "\r\n", codeLines[i]);
     299      }
     300      method.Statements.Add(new CodeSnippetStatement(
     301        string.Join("\r\n", codeLines) +
     302        "\r\nreturn null;"));
     303      return method;
     304    }
     305
     306    #endregion
     307
     308    #region HeuristicLab interfaces
    161309
    162310    public override IOperation Apply(IScope scope) {
     
    167315      }
    168316
    169       // collect parameters
    170       object[] parameters = new object[VariableInfos.Count + 2];
    171       parameters[0] = this;
    172       parameters[1] = scope;
    173       int i = 2;
    174       foreach (IVariableInfo info in VariableInfos) {
    175         if ((info.Kind & VariableKind.New) == VariableKind.New) {
    176           parameters[i] = GetVariableValue(info.FormalName, scope, false, false);
    177           if (parameters[i] == null) {
    178             IItem value = (IItem)Activator.CreateInstance(info.DataType);
    179             if (info.Local) {
    180               AddVariable(new Variable(info.ActualName, value));
    181             } else {
    182               scope.AddVariable(new Variable(scope.TranslateName(info.FormalName), value));
    183             }
    184             parameters[i] = value;
    185           }
    186         } else
    187           parameters[i] = GetVariableValue(info.FormalName, scope, true);
    188         i++;
    189       }
    190 
    191       return (IOperation)executeMethod.Invoke(null, parameters);
     317      var parameters = new List<object>() { this, scope };
     318      parameters.AddRange(VariableInfos.Select(info => GetParameter(info, scope)));
     319      return (IOperation)executeMethod.Invoke(null, parameters.ToArray());
     320    }
     321
     322    private object GetParameter(IVariableInfo info, IScope scope) {
     323      if ((info.Kind & VariableKind.New) != VariableKind.New) {
     324        return GetVariableValue(info.FormalName, scope, true);
     325      } else {
     326        var parameter = GetVariableValue(info.FormalName, scope, false, false);
     327        if (parameter != null)
     328          return parameter;
     329        IItem value = (IItem)Activator.CreateInstance(info.DataType);
     330        if (info.Local) {
     331          AddVariable(new Variable(info.ActualName, value));
     332        } else {
     333          scope.AddVariable(new Variable(scope.TranslateName(info.FormalName), value));
     334        }
     335        return value;
     336      }
    192337    }
    193338
     
    207352    }
    208353
    209     #region Persistence Methods
     354    #endregion
     355
     356    #region Persistence & Cloning
     357
     358    public override object Clone(IDictionary<Guid, object> clonedObjects) {
     359      ProgrammableOperator clone = (ProgrammableOperator)base.Clone(clonedObjects);
     360      clone.description = Description;
     361      clone.code = Code;
     362      clone.executeMethod = executeMethod;
     363      clone.Assemblies = Assemblies.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
     364      clone.namespaces = namespaces;
     365      clone.CompilationUnitCode = CompilationUnitCode;
     366      clone.CompileErrors = CompileErrors;
     367      return clone;
     368    }
     369
    210370    public override XmlNode GetXmlNode(string name, XmlDocument document, IDictionary<Guid, IStorable> persistedObjects) {
    211371      XmlNode node = base.GetXmlNode(name, document, persistedObjects);
     372
    212373      XmlNode descriptionNode = document.CreateNode(XmlNodeType.Element, "Description", null);
    213       descriptionNode.InnerText = myDescription;
     374      descriptionNode.InnerText = description;
    214375      node.AppendChild(descriptionNode);
     376
    215377      XmlNode codeNode = document.CreateNode(XmlNodeType.Element, "Code", null);
    216       codeNode.InnerText = myCode;
     378      codeNode.InnerText = code;
    217379      node.AppendChild(codeNode);
     380
     381      XmlNode assembliesNode = document.CreateNode(XmlNodeType.Element, "Assemblies", null);
     382      foreach (var a in SelectedAssemblies) {
     383        var assemblyNode = document.CreateNode(XmlNodeType.Element, "Assembly", null);
     384        assemblyNode.InnerText = a.FullName;
     385        assembliesNode.AppendChild(assemblyNode);
     386      }
     387      node.AppendChild(assembliesNode);
     388
     389      XmlNode namespacesNode = document.CreateNode(XmlNodeType.Element, "Namespaces", null);
     390      foreach (string ns in namespaces) {
     391        var nsNode = document.CreateNode(XmlNodeType.Element, "Namespace", null);
     392        nsNode.InnerText = ns;
     393        namespacesNode.AppendChild(nsNode);
     394      }
     395      node.AppendChild(namespacesNode);
     396
    218397      return node;
    219398    }
    220399    public override void Populate(XmlNode node, IDictionary<Guid, IStorable> restoredObjects) {
    221400      base.Populate(node, restoredObjects);
     401
    222402      XmlNode descriptionNode = node.SelectSingleNode("Description");
    223       myDescription = descriptionNode.InnerText;
     403      description = descriptionNode.InnerText;
     404
    224405      XmlNode codeNode = node.SelectSingleNode("Code");
    225       myCode = codeNode.InnerText;
    226     }
     406      code = codeNode.InnerText;
     407
     408      XmlNode assembliesNode = node.SelectSingleNode("Assemblies");
     409      if (assembliesNode != null) {
     410        var selectedAssemblyNames = new HashSet<string>();
     411        foreach (XmlNode assemblyNode in assembliesNode.ChildNodes) {
     412          selectedAssemblyNames.Add(assemblyNode.InnerText);
     413        }
     414        var selectedAssemblies = new List<Assembly>();
     415        foreach (var a in Assemblies.Keys.ToList()) {
     416          Assemblies[a] = selectedAssemblyNames.Contains(a.FullName);
     417        }
     418      }
     419      XmlNode namespacesNode = node.SelectSingleNode("Namespaces");
     420      if (namespacesNode != null) {
     421        namespaces.Clear();
     422        var possibleNamespaces = new HashSet<string>(GetAllNamespaces(true));
     423        foreach (XmlNode nsNode in namespacesNode.ChildNodes) {
     424          if (possibleNamespaces.Contains(nsNode.InnerText))
     425            SelectNamespace(nsNode.InnerText);
     426        }
     427      }
     428    }
     429
    227430    #endregion
    228431  }
  • trunk/sources/HeuristicLab.Operators.Programmable/3.2/ProgrammableOperatorView.Designer.cs

    r1530 r2660  
    4545    /// </summary>
    4646    private void InitializeComponent() {
    47       System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ProgrammableOperatorView));
     47      System.Windows.Forms.SplitContainer splitContainer1;
     48      System.Windows.Forms.SplitContainer splitContainer2;
     49      System.Windows.Forms.GroupBox groupBox1;
     50      System.Windows.Forms.GroupBox groupBox2;
     51      this.assembliesListBox = new System.Windows.Forms.CheckedListBox();
     52      this.namespacesListBox = new System.Windows.Forms.CheckedListBox();
     53      this.groupBox3 = new System.Windows.Forms.GroupBox();
     54      this.showCodeButton = new System.Windows.Forms.Button();
     55      this.compileButton = new System.Windows.Forms.Button();
    4856      this.tabControl = new System.Windows.Forms.TabControl();
    4957      this.codeTabPage = new System.Windows.Forms.TabPage();
    50       this.infoTextBox = new System.Windows.Forms.TextBox();
    51       this.compileButton = new System.Windows.Forms.Button();
    52       this.codeTextBox = new System.Windows.Forms.TextBox();
    5358      this.variableInfosTabPage = new System.Windows.Forms.TabPage();
    5459      this.removeVariableInfoButton = new System.Windows.Forms.Button();
     
    6166      this.descriptionTabPage = new System.Windows.Forms.TabPage();
    6267      this.descriptionTextBox = new System.Windows.Forms.TextBox();
     68      this.codeEditor = new HeuristicLab.CodeEditor.CodeEditor();
     69      splitContainer1 = new System.Windows.Forms.SplitContainer();
     70      splitContainer2 = new System.Windows.Forms.SplitContainer();
     71      groupBox1 = new System.Windows.Forms.GroupBox();
     72      groupBox2 = new System.Windows.Forms.GroupBox();
     73      splitContainer1.Panel1.SuspendLayout();
     74      splitContainer1.Panel2.SuspendLayout();
     75      splitContainer1.SuspendLayout();
     76      splitContainer2.Panel1.SuspendLayout();
     77      splitContainer2.Panel2.SuspendLayout();
     78      splitContainer2.SuspendLayout();
     79      groupBox1.SuspendLayout();
     80      groupBox2.SuspendLayout();
     81      this.groupBox3.SuspendLayout();
    6382      this.tabControl.SuspendLayout();
    6483      this.codeTabPage.SuspendLayout();
     
    6887      this.descriptionTabPage.SuspendLayout();
    6988      this.SuspendLayout();
     89      //
     90      // splitContainer1
     91      //
     92      splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
     93      splitContainer1.Location = new System.Drawing.Point(3, 3);
     94      splitContainer1.Name = "splitContainer1";
     95      splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal;
     96      //
     97      // splitContainer1.Panel1
     98      //
     99      splitContainer1.Panel1.Controls.Add(splitContainer2);
     100      //
     101      // splitContainer1.Panel2
     102      //
     103      splitContainer1.Panel2.Controls.Add(this.groupBox3);
     104      splitContainer1.Size = new System.Drawing.Size(693, 457);
     105      splitContainer1.SplitterDistance = 85;
     106      splitContainer1.TabIndex = 6;
     107      //
     108      // splitContainer2
     109      //
     110      splitContainer2.Dock = System.Windows.Forms.DockStyle.Fill;
     111      splitContainer2.Location = new System.Drawing.Point(0, 0);
     112      splitContainer2.Name = "splitContainer2";
     113      //
     114      // splitContainer2.Panel1
     115      //
     116      splitContainer2.Panel1.Controls.Add(groupBox1);
     117      //
     118      // splitContainer2.Panel2
     119      //
     120      splitContainer2.Panel2.Controls.Add(groupBox2);
     121      splitContainer2.Size = new System.Drawing.Size(693, 85);
     122      splitContainer2.SplitterDistance = 340;
     123      splitContainer2.TabIndex = 2;
     124      //
     125      // groupBox1
     126      //
     127      groupBox1.Controls.Add(this.assembliesListBox);
     128      groupBox1.Dock = System.Windows.Forms.DockStyle.Fill;
     129      groupBox1.Location = new System.Drawing.Point(0, 0);
     130      groupBox1.Name = "groupBox1";
     131      groupBox1.Size = new System.Drawing.Size(340, 85);
     132      groupBox1.TabIndex = 0;
     133      groupBox1.TabStop = false;
     134      groupBox1.Text = "Assemblies";
     135      //
     136      // assembliesListBox
     137      //
     138      this.assembliesListBox.CheckOnClick = true;
     139      this.assembliesListBox.Dock = System.Windows.Forms.DockStyle.Fill;
     140      this.assembliesListBox.FormattingEnabled = true;
     141      this.assembliesListBox.Location = new System.Drawing.Point(3, 16);
     142      this.assembliesListBox.Name = "assembliesListBox";
     143      this.assembliesListBox.Size = new System.Drawing.Size(334, 64);
     144      this.assembliesListBox.Sorted = true;
     145      this.assembliesListBox.TabIndex = 0;
     146      this.assembliesListBox.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler(this.assembliesListBox_ItemCheck);
     147      //
     148      // groupBox2
     149      //
     150      groupBox2.Controls.Add(this.namespacesListBox);
     151      groupBox2.Dock = System.Windows.Forms.DockStyle.Fill;
     152      groupBox2.Location = new System.Drawing.Point(0, 0);
     153      groupBox2.Name = "groupBox2";
     154      groupBox2.Size = new System.Drawing.Size(349, 85);
     155      groupBox2.TabIndex = 0;
     156      groupBox2.TabStop = false;
     157      groupBox2.Text = "Namespaces";
     158      //
     159      // namespacesListBox
     160      //
     161      this.namespacesListBox.CheckOnClick = true;
     162      this.namespacesListBox.Dock = System.Windows.Forms.DockStyle.Fill;
     163      this.namespacesListBox.FormattingEnabled = true;
     164      this.namespacesListBox.Location = new System.Drawing.Point(3, 16);
     165      this.namespacesListBox.Name = "namespacesListBox";
     166      this.namespacesListBox.Size = new System.Drawing.Size(343, 64);
     167      this.namespacesListBox.Sorted = true;
     168      this.namespacesListBox.TabIndex = 1;
     169      this.namespacesListBox.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler(this.namespacesListBox_ItemCheck);
     170      //
     171      // groupBox3
     172      //
     173      this.groupBox3.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
     174                  | System.Windows.Forms.AnchorStyles.Left)
     175                  | System.Windows.Forms.AnchorStyles.Right)));
     176      this.groupBox3.Controls.Add(this.showCodeButton);
     177      this.groupBox3.Controls.Add(this.codeEditor);
     178      this.groupBox3.Controls.Add(this.compileButton);
     179      this.groupBox3.Location = new System.Drawing.Point(3, 2);
     180      this.groupBox3.Name = "groupBox3";
     181      this.groupBox3.Size = new System.Drawing.Size(687, 363);
     182      this.groupBox3.TabIndex = 7;
     183      this.groupBox3.TabStop = false;
     184      this.groupBox3.Text = "Code";
     185      //
     186      // showCodeButton
     187      //
     188      this.showCodeButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
     189      this.showCodeButton.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
     190      this.showCodeButton.FlatAppearance.MouseDownBackColor = System.Drawing.SystemColors.ControlDark;
     191      this.showCodeButton.FlatAppearance.MouseOverBackColor = System.Drawing.SystemColors.GradientActiveCaption;
     192      this.showCodeButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
     193      this.showCodeButton.Location = new System.Drawing.Point(467, 333);
     194      this.showCodeButton.Name = "showCodeButton";
     195      this.showCodeButton.Size = new System.Drawing.Size(133, 23);
     196      this.showCodeButton.TabIndex = 7;
     197      this.showCodeButton.Text = "Show Generated Code";
     198      this.showCodeButton.UseVisualStyleBackColor = true;
     199      this.showCodeButton.Click += new System.EventHandler(this.showCodeButton_Click);
     200      //
     201      // compileButton
     202      //
     203      this.compileButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
     204      this.compileButton.Location = new System.Drawing.Point(606, 334);
     205      this.compileButton.Name = "compileButton";
     206      this.compileButton.Size = new System.Drawing.Size(75, 23);
     207      this.compileButton.TabIndex = 3;
     208      this.compileButton.Text = "&Compile";
     209      this.compileButton.UseVisualStyleBackColor = true;
     210      this.compileButton.Click += new System.EventHandler(this.compileButton_Click);
    70211      //
    71212      // tabControl
     
    80221      this.tabControl.Name = "tabControl";
    81222      this.tabControl.SelectedIndex = 0;
    82       this.tabControl.Size = new System.Drawing.Size(435, 351);
     223      this.tabControl.Size = new System.Drawing.Size(707, 489);
    83224      this.tabControl.TabIndex = 0;
    84225      //
    85226      // codeTabPage
    86227      //
    87       this.codeTabPage.Controls.Add(this.infoTextBox);
    88       this.codeTabPage.Controls.Add(this.compileButton);
    89       this.codeTabPage.Controls.Add(this.codeTextBox);
     228      this.codeTabPage.Controls.Add(splitContainer1);
    90229      this.codeTabPage.Location = new System.Drawing.Point(4, 22);
    91230      this.codeTabPage.Name = "codeTabPage";
    92231      this.codeTabPage.Padding = new System.Windows.Forms.Padding(3);
    93       this.codeTabPage.Size = new System.Drawing.Size(427, 325);
     232      this.codeTabPage.Size = new System.Drawing.Size(699, 463);
    94233      this.codeTabPage.TabIndex = 5;
    95234      this.codeTabPage.Text = "Code";
    96235      this.codeTabPage.UseVisualStyleBackColor = true;
    97       //
    98       // infoTextBox
    99       //
    100       this.infoTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
    101                   | System.Windows.Forms.AnchorStyles.Right)));
    102       this.infoTextBox.BackColor = System.Drawing.SystemColors.ControlLight;
    103       this.infoTextBox.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
    104       this.infoTextBox.Location = new System.Drawing.Point(6, 253);
    105       this.infoTextBox.Multiline = true;
    106       this.infoTextBox.Name = "infoTextBox";
    107       this.infoTextBox.ReadOnly = true;
    108       this.infoTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
    109       this.infoTextBox.Size = new System.Drawing.Size(334, 66);
    110       this.infoTextBox.TabIndex = 2;
    111       this.infoTextBox.Text = resources.GetString("infoTextBox.Text");
    112       //
    113       // compileButton
    114       //
    115       this.compileButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
    116       this.compileButton.Location = new System.Drawing.Point(346, 296);
    117       this.compileButton.Name = "compileButton";
    118       this.compileButton.Size = new System.Drawing.Size(75, 23);
    119       this.compileButton.TabIndex = 1;
    120       this.compileButton.Text = "&Compile";
    121       this.compileButton.UseVisualStyleBackColor = true;
    122       this.compileButton.Click += new System.EventHandler(this.compileButton_Click);
    123       //
    124       // codeTextBox
    125       //
    126       this.codeTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
    127                   | System.Windows.Forms.AnchorStyles.Left)
    128                   | System.Windows.Forms.AnchorStyles.Right)));
    129       this.codeTextBox.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
    130       this.codeTextBox.Location = new System.Drawing.Point(3, 3);
    131       this.codeTextBox.Multiline = true;
    132       this.codeTextBox.Name = "codeTextBox";
    133       this.codeTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
    134       this.codeTextBox.Size = new System.Drawing.Size(421, 244);
    135       this.codeTextBox.TabIndex = 0;
    136       this.codeTextBox.Validated += new System.EventHandler(this.codeTextBox_Validated);
    137236      //
    138237      // variableInfosTabPage
     
    144243      this.variableInfosTabPage.Name = "variableInfosTabPage";
    145244      this.variableInfosTabPage.Padding = new System.Windows.Forms.Padding(3);
    146       this.variableInfosTabPage.Size = new System.Drawing.Size(427, 325);
     245      this.variableInfosTabPage.Size = new System.Drawing.Size(699, 463);
    147246      this.variableInfosTabPage.TabIndex = 1;
    148247      this.variableInfosTabPage.Text = "Variable Infos";
     
    153252      this.removeVariableInfoButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
    154253      this.removeVariableInfoButton.Enabled = false;
    155       this.removeVariableInfoButton.Location = new System.Drawing.Point(84, 299);
     254      this.removeVariableInfoButton.Location = new System.Drawing.Point(87, 434);
    156255      this.removeVariableInfoButton.Name = "removeVariableInfoButton";
    157256      this.removeVariableInfoButton.Size = new System.Drawing.Size(75, 23);
     
    164263      //
    165264      this.addVariableInfoButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
    166       this.addVariableInfoButton.Location = new System.Drawing.Point(3, 299);
     265      this.addVariableInfoButton.Location = new System.Drawing.Point(6, 434);
    167266      this.addVariableInfoButton.Name = "addVariableInfoButton";
    168267      this.addVariableInfoButton.Size = new System.Drawing.Size(75, 23);
     
    181280      this.operatorBaseVariableInfosView.Name = "operatorBaseVariableInfosView";
    182281      this.operatorBaseVariableInfosView.Operator = null;
    183       this.operatorBaseVariableInfosView.Size = new System.Drawing.Size(421, 290);
     282      this.operatorBaseVariableInfosView.Size = new System.Drawing.Size(690, 425);
    184283      this.operatorBaseVariableInfosView.TabIndex = 0;
    185284      this.operatorBaseVariableInfosView.SelectedVariableInfosChanged += new System.EventHandler(this.operatorBaseVariableInfosView_SelectedVariableInfosChanged);
     
    191290      this.variablesTabPage.Name = "variablesTabPage";
    192291      this.variablesTabPage.Padding = new System.Windows.Forms.Padding(3);
    193       this.variablesTabPage.Size = new System.Drawing.Size(427, 325);
     292      this.variablesTabPage.Size = new System.Drawing.Size(699, 463);
    194293      this.variablesTabPage.TabIndex = 2;
    195294      this.variablesTabPage.Text = "Local Variables";
     
    203302      this.operatorBaseVariablesView.Name = "operatorBaseVariablesView";
    204303      this.operatorBaseVariablesView.Operator = null;
    205       this.operatorBaseVariablesView.Size = new System.Drawing.Size(421, 319);
     304      this.operatorBaseVariablesView.Size = new System.Drawing.Size(693, 457);
    206305      this.operatorBaseVariablesView.TabIndex = 0;
    207306      //
     
    212311      this.constraintsTabPage.Name = "constraintsTabPage";
    213312      this.constraintsTabPage.Padding = new System.Windows.Forms.Padding(3);
    214       this.constraintsTabPage.Size = new System.Drawing.Size(427, 325);
     313      this.constraintsTabPage.Size = new System.Drawing.Size(699, 463);
    215314      this.constraintsTabPage.TabIndex = 3;
    216315      this.constraintsTabPage.Text = "Constraints";
     
    224323      this.constrainedItemBaseView.Location = new System.Drawing.Point(3, 3);
    225324      this.constrainedItemBaseView.Name = "constrainedItemBaseView";
    226       this.constrainedItemBaseView.Size = new System.Drawing.Size(421, 319);
     325      this.constrainedItemBaseView.Size = new System.Drawing.Size(693, 457);
    227326      this.constrainedItemBaseView.TabIndex = 0;
    228327      //
     
    233332      this.descriptionTabPage.Name = "descriptionTabPage";
    234333      this.descriptionTabPage.Padding = new System.Windows.Forms.Padding(3);
    235       this.descriptionTabPage.Size = new System.Drawing.Size(427, 325);
     334      this.descriptionTabPage.Size = new System.Drawing.Size(699, 463);
    236335      this.descriptionTabPage.TabIndex = 4;
    237336      this.descriptionTabPage.Text = "Description";
     
    246345      this.descriptionTextBox.Name = "descriptionTextBox";
    247346      this.descriptionTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
    248       this.descriptionTextBox.Size = new System.Drawing.Size(421, 319);
     347      this.descriptionTextBox.Size = new System.Drawing.Size(693, 457);
    249348      this.descriptionTextBox.TabIndex = 0;
    250349      this.descriptionTextBox.Validated += new System.EventHandler(this.descriptionTextBox_Validated);
     350      //
     351      // codeEditor
     352      //
     353      this.codeEditor.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
     354                  | System.Windows.Forms.AnchorStyles.Left)
     355                  | System.Windows.Forms.AnchorStyles.Right)));
     356      this.codeEditor.Location = new System.Drawing.Point(6, 19);
     357      this.codeEditor.Name = "codeEditor";
     358      this.codeEditor.Prefix = "using System;\r\nusing HeuristicLab.Common.Resources;\r\n\r\npublic class Operator {\r\n " +
     359          " public static void Apply(int arg) {";
     360      this.codeEditor.Size = new System.Drawing.Size(675, 309);
     361      this.codeEditor.Suffix = "\n    return null;\n  }\n}";
     362      this.codeEditor.TabIndex = 6;
     363      this.codeEditor.UserCode = "\n\n\n";
     364      this.codeEditor.TextEditorValidated += new System.EventHandler(this.codeEditor_Validated);
    251365      //
    252366      // ProgrammableOperatorView
     
    256370      this.Controls.Add(this.tabControl);
    257371      this.Name = "ProgrammableOperatorView";
    258       this.Size = new System.Drawing.Size(435, 351);
     372      this.Size = new System.Drawing.Size(707, 489);
     373      splitContainer1.Panel1.ResumeLayout(false);
     374      splitContainer1.Panel2.ResumeLayout(false);
     375      splitContainer1.ResumeLayout(false);
     376      splitContainer2.Panel1.ResumeLayout(false);
     377      splitContainer2.Panel2.ResumeLayout(false);
     378      splitContainer2.ResumeLayout(false);
     379      groupBox1.ResumeLayout(false);
     380      groupBox2.ResumeLayout(false);
     381      this.groupBox3.ResumeLayout(false);
    259382      this.tabControl.ResumeLayout(false);
    260383      this.codeTabPage.ResumeLayout(false);
    261       this.codeTabPage.PerformLayout();
    262384      this.variableInfosTabPage.ResumeLayout(false);
    263385      this.variablesTabPage.ResumeLayout(false);
     
    273395    private System.Windows.Forms.TabControl tabControl;
    274396    private System.Windows.Forms.TabPage codeTabPage;
    275     private System.Windows.Forms.TextBox codeTextBox;
    276397    private System.Windows.Forms.TabPage variableInfosTabPage;
    277398    private HeuristicLab.Core.OperatorBaseVariableInfosView operatorBaseVariableInfosView;
     
    282403    private System.Windows.Forms.TabPage descriptionTabPage;
    283404    private System.Windows.Forms.TextBox descriptionTextBox;
    284     private System.Windows.Forms.Button compileButton;
    285405    private System.Windows.Forms.Button removeVariableInfoButton;
    286406    private System.Windows.Forms.Button addVariableInfoButton;
    287     private System.Windows.Forms.TextBox infoTextBox;
     407    private System.Windows.Forms.CheckedListBox assembliesListBox;
     408    private System.Windows.Forms.CheckedListBox namespacesListBox;
     409    private System.Windows.Forms.GroupBox groupBox3;
     410    private HeuristicLab.CodeEditor.CodeEditor codeEditor;
     411    private System.Windows.Forms.Button compileButton;
     412    private System.Windows.Forms.Button showCodeButton;
    288413
    289414  }
  • trunk/sources/HeuristicLab.Operators.Programmable/3.2/ProgrammableOperatorView.cs

    r1530 r2660  
    2626using System.Data;
    2727using System.Text;
     28using System.Linq;
    2829using System.Windows.Forms;
    2930using HeuristicLab.Core;
    3031using HeuristicLab.Operators;
     32using System.CodeDom.Compiler;
     33using System.Reflection;
     34using HeuristicLab.CodeEditor;
    3135
    3236namespace HeuristicLab.Operators.Programmable {
     37
    3338  public partial class ProgrammableOperatorView : ViewBase {
     39
    3440    public ProgrammableOperator ProgrammableOperator {
    3541      get { return (ProgrammableOperator)Item; }
     
    4046      InitializeComponent();
    4147    }
     48
    4249    public ProgrammableOperatorView(ProgrammableOperator programmableOperator)
    4350      : this() {
    4451      ProgrammableOperator = programmableOperator;
    4552    }
    46 
     53   
    4754    protected override void RemoveItemEvents() {
    4855      operatorBaseVariableInfosView.Operator = null;
     
    6673      base.UpdateControls();
    6774      if (ProgrammableOperator == null) {
    68         codeTextBox.Text = "";
    69         codeTextBox.Enabled = false;
     75        codeEditor.Text = "";
     76        codeEditor.Enabled = false;
    7077        addVariableInfoButton.Enabled = false;
    7178        removeVariableInfoButton.Enabled = false;
    7279        descriptionTextBox.Text = "";
    7380        descriptionTextBox.Enabled = false;
    74       } else {
    75         codeTextBox.Text = ProgrammableOperator.Code;
    76         codeTextBox.Enabled = true;
     81        codeEditor.Prefix = @"using System
     82
     83public class Operator {
     84  public static IOperation Execute(IOperator op, IScope scope, parameters ...) {";
     85        codeEditor.Suffix = @"
     86    return null;
     87  }
     88}";   
     89        assembliesListBox.DataSource = null;
     90      } else {       
     91        codeEditor.Enabled = true;
    7792        addVariableInfoButton.Enabled = true;
    7893        removeVariableInfoButton.Enabled = operatorBaseVariableInfosView.SelectedVariableInfos.Count > 0;
    7994        descriptionTextBox.Text = ProgrammableOperator.Description;
    8095        descriptionTextBox.Enabled = true;
    81       }
     96        codeEditor.Prefix = GetGeneratedPrefix();
     97        codeEditor.Suffix = @"
     98    return null;
     99  }
     100}";
     101        codeEditor.UserCode = ProgrammableOperator.Code;
     102        if (codeEditor.UserCode == "")
     103          codeEditor.UserCode = "\n\n\n";
     104        InitializeAssemblyList();
     105        InitializeNamespacesList();
     106        foreach (var a in ProgrammableOperator.SelectedAssemblies) {
     107          codeEditor.AddAssembly(a);
     108        }
     109        codeEditor.ScrollAfterPrefix();
     110      }     
     111    }
     112
     113   
     114    private string GetGeneratedPrefix() {
     115      StringBuilder prefix = new StringBuilder();
     116      foreach (var ns in ProgrammableOperator.GetSelectedAndValidNamespaces()) {
     117        prefix.Append("using ").Append(ns).AppendLine(";");
     118      }
     119      prefix.AppendLine();
     120      prefix.Append("public class ").Append(ProgrammableOperator.CompiledTypeName).AppendLine(" {");
     121      prefix.Append("  ").Append(ProgrammableOperator.Signature).Append(" {");
     122      return prefix.ToString();
    82123    }
    83124
     
    85126      removeVariableInfoButton.Enabled = operatorBaseVariableInfosView.SelectedVariableInfos.Count > 0;
    86127    }
    87 
    88     #region Validated Events
    89     private void codeTextBox_Validated(object sender, EventArgs e) {
    90       ProgrammableOperator.Code = codeTextBox.Text;
     128    private void codeEditor_Validated(object sender, EventArgs e) {
     129      ProgrammableOperator.Code = codeEditor.UserCode;
    91130    }
    92131    private void descriptionTextBox_Validated(object sender, EventArgs e) {
    93132      ProgrammableOperator.SetDescription(descriptionTextBox.Text);
    94133    }
    95     #endregion
    96 
    97     #region Click Events
    98     private void compileButton_Click(object sender, EventArgs e) {
    99       try {
    100         ProgrammableOperator.Compile();
    101         MessageBox.Show("Compilation successful", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
    102       }
    103       catch (Exception ex) {
    104         Auxiliary.ShowErrorMessageBox(ex);
    105       }
    106     }
     134
    107135    private void addVariableInfoButton_Click(object sender, EventArgs e) {
    108136      AddVariableInfoDialog dialog = new AddVariableInfoDialog();
    109137      if (dialog.ShowDialog(this) == DialogResult.OK) {
    110         if (ProgrammableOperator.GetVariableInfo(dialog.VariableInfo.FormalName) != null)
     138        if (ProgrammableOperator.GetVariableInfo(dialog.VariableInfo.FormalName) != null) {
    111139          Auxiliary.ShowErrorMessageBox("A variable info with the same formal name already exists.");
    112         else
     140        } else {
    113141          ProgrammableOperator.AddVariableInfo(dialog.VariableInfo);
     142          Recompile();         
     143        }
    114144      }
    115145      dialog.Dispose();
    116146    }
     147
    117148    private void removeVariableInfoButton_Click(object sender, EventArgs e) {
    118149      IVariableInfo[] selected = new IVariableInfo[operatorBaseVariableInfosView.SelectedVariableInfos.Count];
     
    121152        ProgrammableOperator.RemoveVariableInfo(selected[i].FormalName);
    122153    }
    123     #endregion
     154
     155    private void Recompile() {
     156      try {
     157        ProgrammableOperator.Compile();       
     158        MessageBox.Show("Compilation successful", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
     159      } catch (Exception ex) {
     160        Auxiliary.ShowErrorMessageBox(ex);
     161      }
     162      UpdateControls();
     163      codeEditor.ShowCompileErrors(ProgrammableOperator.CompileErrors, "ProgrammableOperator");     
     164    }
     165
     166    private void compileButton_Click(object sender, EventArgs e) {
     167      Recompile();
     168    }   
    124169
    125170    #region ProgrammableOperator Events
    126171    private void ProgrammableOperator_CodeChanged(object sender, EventArgs e) {
    127       codeTextBox.Text = ProgrammableOperator.Code;
     172      codeEditor.Text = ProgrammableOperator.Code;
    128173    }
    129174    private void ProgrammableOperator_DescriptionChanged(object sender, EventArgs e) {
     
    131176    }
    132177    #endregion
     178
     179    public static Assembly GetAssembly(CheckedListBox box, int index) {
     180      return (Assembly)(((CheckedListBoxItem)box.Items[index]).Tag);
     181    }
     182
     183    private void assembliesListBox_ItemCheck(object sender, ItemCheckEventArgs e) {
     184      if (initializing)
     185        return;
     186      Assembly a = GetAssembly(assembliesListBox, e.Index);
     187      if (e.NewValue == CheckState.Checked) {               
     188        ProgrammableOperator.SelectAssembly(a);
     189        codeEditor.AddAssembly(a);
     190      } else if (e.NewValue == CheckState.Unchecked) {
     191        ProgrammableOperator.UnselectAssembly(a);
     192        codeEditor.RemoveAssembly(a);
     193      } else {
     194        return;
     195      }
     196      InitializeNamespacesList();     
     197      codeEditor.Prefix = GetGeneratedPrefix();
     198    }
     199
     200    private bool initializing = false;
     201    private void InitializeAssemblyList() {
     202      assembliesListBox.Items.Clear();
     203      var selectedAssemblies = new HashSet<Assembly>(ProgrammableOperator.SelectedAssemblies);
     204      initializing = true;
     205      foreach (var a in ProgrammableOperator.AvailableAssemblies.ToList()) {
     206        assembliesListBox.Items.Add(
     207          new CheckedListBoxItem(a.GetName().Name, a),
     208          selectedAssemblies.Contains(a));
     209      }
     210      initializing = false;
     211    }
     212
     213    private void InitializeNamespacesList() {
     214      initializing = true;
     215      namespacesListBox.Items.Clear();
     216      var selectedNamespaces = new HashSet<string>(ProgrammableOperator.Namespaces);
     217      foreach (var ns in ProgrammableOperator.GetAllNamespaces(true)) {
     218        namespacesListBox.Items.Add(ns, selectedNamespaces.Contains(ns));
     219      }
     220      codeEditor.Prefix = GetGeneratedPrefix();
     221      initializing = false;
     222    }
     223
     224    private void namespacesListBox_ItemCheck(object sender, ItemCheckEventArgs e) {
     225      if (initializing)
     226        return;
     227      if (e.NewValue == CheckState.Checked) {
     228        ProgrammableOperator.SelectNamespace((string)namespacesListBox.Items[e.Index]);
     229      } else if (e.NewValue == CheckState.Unchecked) {
     230        ProgrammableOperator.UnselectNamespace((string)namespacesListBox.Items[e.Index]);
     231      }
     232      codeEditor.Prefix = GetGeneratedPrefix();
     233    }
     234
     235    private void showCodeButton_Click(object sender, EventArgs e) {
     236      new CodeViewer(ProgrammableOperator.CompilationUnitCode).ShowDialog(this);
     237    }
     238
     239  }
     240
     241  public class CheckedListBoxItem : IComparable {
     242
     243    public object Tag { get; private set; }
     244    public string Text { get; private set; }
     245
     246    public CheckedListBoxItem(string text, object tag) {
     247      Text = text;
     248      Tag = tag;
     249    }
     250
     251    public override string ToString() {
     252      return Text;
     253    }
     254
     255    public int CompareTo(object obj) {
     256      if (obj == null)
     257        throw new ArgumentException("cannot compare to null");
     258      if (!(obj is CheckedListBoxItem))
     259        throw new ArgumentException(string.Format(
     260          "cannot compare CheckedListBoxItem to {0}",
     261          obj.GetType().Name));
     262      return Text.CompareTo(((CheckedListBoxItem)obj).Text);
     263    }
    133264  }
    134265}
  • trunk/sources/HeuristicLab.Operators.Programmable/3.2/ProgrammableOperatorView.resx

    r1530 r2660  
    118118    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
    119119  </resheader>
    120   <data name="infoTextBox.Text" xml:space="preserve">
    121     <value>All variables corresponding to declared variable infos can be accessed directly using their formal names. Additionally there are two special variables: "op" referring to the programmable operator itself (this) and "scope" referring to the scope the operator is applied on.</value>
    122   </data>
     120  <metadata name="splitContainer1.GenerateMember" type="System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
     121    <value>False</value>
     122  </metadata>
     123  <metadata name="splitContainer2.GenerateMember" type="System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
     124    <value>False</value>
     125  </metadata>
     126  <metadata name="groupBox1.GenerateMember" type="System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
     127    <value>False</value>
     128  </metadata>
     129  <metadata name="groupBox2.GenerateMember" type="System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
     130    <value>False</value>
     131  </metadata>
    123132</root>
  • trunk/sources/HeuristicLab/Files.txt

    r2657 r2660  
    1212HeuristicLab.CEDMA.Server\3.3:HeuristicLab.CEDMA.Server-3.3.dll
    1313
     14HeuristicLab.CodeEditor\3.2:HeuristicLab.CodeEditor-3.2.dll
    1415HeuristicLab.Charting\3.2:HeuristicLab.Charting-3.2.dll
    1516HeuristicLab.Charting.Data\3.2:HeuristicLab.Charting.Data-3.2.dll
     
    148149HeuristicLab.ExtLibs\HeuristicLab.WinFormsUI\2.3.1\HeuristicLab.WinFormsUI-2.3.1:HeuristicLab.WinFormsUI-2.3.1.dll
    149150HeuristicLab.ExtLibs\HeuristicLab.WinFormsUI\2.3.1\HeuristicLab.WinFormsUI-2.3.1:WeifenLuo.WinFormsUI.Docking License.txt
     151
     152HeuristicLab.ExtLibs\HeuristicLab.SharpDevelop\3.1.1.5327:ICSharpCode.NRefactory.dll
     153HeuristicLab.ExtLibs\HeuristicLab.SharpDevelop\3.1.1.5327:ICSharpCode.SharpDevelop.Dom.dll
     154HeuristicLab.ExtLibs\HeuristicLab.SharpDevelop\3.1.1.5327:ICSharpCode.TextEditor.dll
     155HeuristicLab.ExtLibs\HeuristicLab.SharpDevelop\3.1.1.5327:Mono.Cecil.dll
     156HeuristicLab.ExtLibs\HeuristicLab.SharpDevelop\3.1.1.5327:SharpDevelop License.txt
     157HeuristicLab.ExtLibs\HeuristicLab.SharpDevelop\3.1.1.5327:Mono License.txt
     158
Note: See TracChangeset for help on using the changeset viewer.