Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ParameterBinding/HeuristicLab.Parameters/3.3/LookupParameter.cs @ 10888

Last change on this file since 10888 was 4722, checked in by swagner, 14 years ago

Merged cloning refactoring branch back into trunk (#922)

File size: 6.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 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 HeuristicLab.Common;
24using HeuristicLab.Core;
25using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
26
27namespace HeuristicLab.Parameters {
28  /// <summary>
29  /// A parameter whose value is retrieved from the scope.
30  /// </summary>
31  [Item("LookupParameter", "A parameter whose value is retrieved from or written to a scope.")]
32  [StorableClass]
33  public class LookupParameter<T> : Parameter, ILookupParameter<T> where T : class, IItem {
34    [Storable]
35    private string actualName;
36    public string ActualName {
37      get { return actualName; }
38      set {
39        if (value == null) throw new ArgumentNullException();
40        if (!actualName.Equals(value)) {
41          actualName = value;
42          OnActualNameChanged();
43        }
44      }
45    }
46    public string TranslatedName {
47      get {
48        string translatedName;
49        GetValueParameterAndTranslateName(out translatedName);
50        return translatedName;
51      }
52    }
53    public new T ActualValue {
54      get {
55        if (cachedActualValue == null) cachedActualValue = GetActualValue();
56        return (T)cachedActualValue;
57      }
58      set {
59        cachedActualValue = value;
60        SetActualValue(value);
61      }
62    }
63
64    [StorableConstructor]
65    protected LookupParameter(bool deserializing) : base(deserializing) { }
66    protected LookupParameter(LookupParameter<T> original, Cloner cloner)
67      : base(original, cloner) {
68      actualName = original.actualName;
69    }
70    public LookupParameter()
71      : base("Anonymous", typeof(T)) {
72      this.actualName = Name;
73    }
74    public LookupParameter(string name)
75      : base(name, typeof(T)) {
76      this.actualName = Name;
77    }
78    public LookupParameter(string name, string description)
79      : base(name, description, typeof(T)) {
80      this.actualName = Name;
81    }
82    public LookupParameter(string name, string description, string actualName)
83      : base(name, description, typeof(T)) {
84      this.actualName = actualName == null ? string.Empty : actualName;
85    }
86
87    public override IDeepCloneable Clone(Cloner cloner) {
88      return new LookupParameter<T>(this, cloner);
89    }
90
91    public override string ToString() {
92      if (Name.Equals(ActualName))
93        return Name;
94      else
95        return Name + ": " + ActualName;
96    }
97
98    private IValueParameter GetValueParameterAndTranslateName(out string actualName) {
99      IValueParameter valueParam;
100      ILookupParameter lookupParam;
101      IExecutionContext currentExecutionContext = ExecutionContext;
102
103      actualName = Name;
104      while (currentExecutionContext != null) {
105        valueParam = currentExecutionContext.Parameters[actualName] as IValueParameter;
106        lookupParam = currentExecutionContext.Parameters[actualName] as ILookupParameter;
107
108        if ((valueParam == null) && (lookupParam == null))
109          throw new InvalidOperationException(
110            string.Format("Parameter look-up chain broken. Parameter \"{0}\" is not an \"{1}\" or an \"{2}\".",
111                          actualName, typeof(IValueParameter).GetPrettyName(), typeof(ILookupParameter).GetPrettyName())
112          );
113
114        if (valueParam != null) {
115          if (valueParam.Value != null) return valueParam;
116          else if (lookupParam == null) return valueParam;
117        }
118        if (lookupParam != null) actualName = lookupParam.ActualName;
119
120        currentExecutionContext = currentExecutionContext.Parent;
121        while ((currentExecutionContext != null) && !currentExecutionContext.Parameters.ContainsKey(actualName))
122          currentExecutionContext = currentExecutionContext.Parent;
123      }
124      return null;
125    }
126    private IVariable LookupVariable(string name) {
127      IScope scope = ExecutionContext.Scope;
128      while ((scope != null) && !scope.Variables.ContainsKey(name))
129        scope = scope.Parent;
130      return scope != null ? scope.Variables[name] : null;
131    }
132    protected override IItem GetActualValue() {
133      string name;
134      // try to get value from context stack
135      IValueParameter param = GetValueParameterAndTranslateName(out name);
136      if (param != null) return param.Value;
137
138      // try to get variable from scope
139      IVariable var = LookupVariable(name);
140      if (var != null) {
141        if (!(var.Value is T))
142          throw new InvalidOperationException(
143            string.Format("Type mismatch. Variable \"{0}\" does not contain a \"{1}\".",
144                          name,
145                          typeof(T).GetPrettyName())
146          );
147        return var.Value;
148      }
149      return null;
150    }
151    protected override void SetActualValue(IItem value) {
152      if (!(value is T))
153        throw new InvalidOperationException(
154          string.Format("Type mismatch. Value is not a \"{0}\".",
155                        typeof(T).GetPrettyName())
156        );
157      // try to set value in context stack
158      string name;
159      IValueParameter param = GetValueParameterAndTranslateName(out name);
160      if (param != null) {
161        param.Value = value;
162        return;
163      }
164
165      // try to set value in scope
166      IVariable var = LookupVariable(name);
167      if (var != null) {
168        var.Value = value;
169        return;
170      }
171
172      // create new variable
173      ExecutionContext.Scope.Variables.Add(new Variable(name, value));
174    }
175
176    public event EventHandler ActualNameChanged;
177    protected virtual void OnActualNameChanged() {
178      EventHandler handler = ActualNameChanged;
179      if (handler != null) handler(this, EventArgs.Empty);
180      OnToStringChanged();
181    }
182  }
183}
Note: See TracBrowser for help on using the repository browser.