Free cookie consent management tool by TermsFeed Policy Generator

source: branches/OKB/HeuristicLab.OKB.Cockpit.Admin/ProblemEditor.xaml.cs @ 4480

Last change on this file since 4480 was 4311, checked in by swagner, 14 years ago

Integrated OKB clients for HL 3.3 (#1166)

File size: 10.9 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using HeuristicLab.MainForm.WPF;
6using System.Windows.Controls;
7using System.Windows;
8using HeuristicLab.BackgroundProcessing;
9using System.Diagnostics;
10using System.IO;
11using HeuristicLab.Persistence.Default.Xml;
12using HeuristicLab.Persistence.Core;
13using System.Collections.ObjectModel;
14using HeuristicLab.MainForm;
15using System.Data;
16using System.Globalization;
17using HeuristicLab.OKB.Client;
18
19namespace HeuristicLab.OKB.Cockpit.Admin {
20  public partial class ProblemEditor : UserControl, IView, IOKBCockpitItem {
21
22    public static DependencyProperty ProblemProperty = DependencyProperty.Register(
23      "Problem", typeof(OKBAdmin.Problem), typeof(AlgorithmEditor));
24
25    public OKBAdmin.Problem Problem {
26      get { return (OKBAdmin.Problem)GetValue(ProblemProperty); }
27      set { SetValue(ProblemProperty, value); }
28    }
29
30    private Dictionary<int, Type> dataTypes;
31
32    public ProblemEditor() {
33      InitializeComponent();
34      Problem = null;
35      InitializeSolutionRepresentations();
36      InitializeDataTypes();
37      InitializeProblemCharacteristics();
38    }
39
40    protected void InitializeDataTypes() {
41      dataTypes = new Dictionary<int, Type>();
42      var loader = new TableLoadWorker("DataType", false);
43      loader.RunWorkerCompleted += (s, a) => {
44        foreach (DataRow row in loader.Table.Rows) {
45          try {
46            dataTypes.Add((int)row["Id"], Type.GetType((string)row["clrName"]));
47          } catch (Exception x) {
48            MessageBox.Show(
49              String.Format("Could not parse CLR name of database datatype '{0}':\n{1}", row["clrName"], x),
50              Caption, MessageBoxButton.OK, MessageBoxImage.Error);
51          }
52        }
53      };
54      loader.RunWorkerAsync();
55    }
56
57    protected void InitializeProblemCharacteristics() {
58      var loader = new TableLoadWorker("ProblemCharacteristic", false);
59      loader.RunWorkerCompleted += (s, a) => {
60        if (loader.Table != null) {
61          loader.Table.Columns.Add(new DataColumn("Value", typeof(string)));
62          loader.Table.Columns.Add(new DataColumn("IsSelected", typeof(bool)));
63          loader.Table.Columns.Add(new DataColumn("DataType", typeof(Type)));
64          foreach (DataRow row in loader.Table.Rows) {
65            try {
66              row["IsSelected"] = false;
67              row["DataType"] = dataTypes[(int)row["DataTypeId"]];
68            } catch { }
69          }
70          ProblemCharacteristicsList.ItemsSource = loader.Table.DefaultView;
71        }
72      };
73      loader.RunWorkerAsync();
74    }
75
76    protected void InitializeSolutionRepresentations() {
77      var loader = new TableLoadWorker("SolutionRepresentation", false);
78      loader.RunWorkerCompleted += (s, a) => {
79        if (loader.Table != null) {
80          SolutionRepresentationBox.ItemsSource = loader.Table.DefaultView;
81        }
82      };
83      loader.RunWorkerAsync();
84    }
85
86    protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e) {
87      base.OnPropertyChanged(e);
88      if (e.Property == ProblemProperty)
89        UpdateProblem();
90    }
91
92    private void UpdateProblem() {
93      if (Problem == null) {
94        Clear();
95        return;
96      }
97      OnLoad(this, new RoutedEventArgs());
98    }
99
100    private void Clear() {
101      IdBox.Text = null;
102      NameBox.Text = null;
103      DescriptionBox.Text = null;
104    }
105
106    private bool isLoading = false;
107    protected void OnLoad(object sender, RoutedEventArgs args) {
108      if (isLoading) return;
109      isLoading = true;
110      var loader = new ObservableBackgroundWorker("downloading problem") {
111        WorkerSupportsCancellation = true,
112        WorkerReportsProgress = true,
113      };
114      OKBAdmin.Problem problem = Problem;
115      loader.DoWork += (s, a) => {
116        OKBAdmin.AdminServiceClient client = ClientFactory.Create<OKBAdmin.AdminServiceClient, OKBAdmin.IAdminService>();
117        problem = client.GetCompleteProblem(problem.Id);
118        client.Close();
119        loader.ReportProgress(10);       
120        byte[] data = new DataClientHelper(loader, a) {
121          ReportProgress = p => loader.ReportProgress(10 + 80 * p / 100),
122        }.Load(OKBData.EntityType.Problem, problem.Id);
123        if (data != null && !loader.CancellationPending) {
124          OperatorGraphEditor.LoadData(data, problem.Platform, OperatorGraphEditorHost.EditorType.Problem);
125          loader.ReportProgress(100);
126        }
127      };
128      loader.RunWorkerCompleted += (s, a) => {
129        try {
130          if (problem == null) return;
131          Problem = problem;
132          IdBox.Text = Problem.Id.ToString();
133          NameBox.Text = Problem.Name;
134          DescriptionBox.Text = Problem.Description;
135          SolutionRepresentationBox.SelectedItem =
136            SolutionRepresentationBox.Items.Cast<DataRowView>()
137            .SingleOrDefault(sr => (int)sr["Id"] == Problem.SolutionRepresentation.Id);
138          LoadProblemCharacteristics();
139        } finally {
140          isLoading = false;
141        }
142      };
143      loader.RunWorkerAsync();
144    }
145
146    protected void LoadProblemCharacteristics() {
147      var pcs = new Dictionary<int, object>();
148      foreach (var pc in Problem.IntProblemCharacteristicValues)
149        pcs.Add(pc.ProblemCharacteristicId, pc.Value);
150      foreach (var pc in Problem.CharProblemCharacteristicValues)
151        pcs.Add(pc.ProblemCharacteristicId, pc.Value);
152      foreach (var pc in Problem.FloatProblemCharacteristicValues)
153        pcs.Add(pc.ProblemCharacteristicId, pc.Value);
154      foreach (DataRowView row in ProblemCharacteristicsList.Items) {
155        int id = (int)row["Id"];
156        if (pcs.ContainsKey(id)) {
157          row["IsSelected"] = true;
158          row["Value"] = pcs[id].ToString();
159        }
160      }
161    }
162
163    protected void OnSave(object sender, RoutedEventArgs args) {
164      StoreProblemCharacteristics();
165      Problem.Name = NameBox.Text;
166      Problem.Description = DescriptionBox.Text;
167      OKBAdmin.Problem problem = Problem;
168      OperatorGraphEditorHost editor = OperatorGraphEditor;
169      var saver = new ObservableBackgroundWorker("uploading problem") {
170        WorkerReportsProgress = true,
171        WorkerSupportsCancellation = true,
172      };
173      saver.DoWork += (s, a) => {
174        OKBAdmin.AdminServiceClient client = ClientFactory.Create<OKBAdmin.AdminServiceClient, OKBAdmin.IAdminService>();       
175        client.UpdateCompleteProblem(problem);
176        client.Close();
177        saver.ReportProgress(10);
178        byte[] data = editor.GetProblemData();
179        saver.ReportProgress(20);
180        if (data != null) {
181          new DataClientHelper(saver, a) {
182            ReportProgress = i => saver.ReportProgress(20 + 80 * i / 100)
183          }.Save(OKBData.EntityType.Problem, problem.Id, data);
184        } else {
185          saver.ReportProgress(100);
186        }
187      };
188      saver.RunWorkerAsync();
189    }
190
191    private void StoreProblemCharacteristics() {
192      Problem.IntProblemCharacteristicValues.Clear();
193      Problem.FloatProblemCharacteristicValues.Clear();
194      Problem.CharProblemCharacteristicValues.Clear();
195      foreach (DataRowView row in ProblemCharacteristicsList.Items) {
196        string value = row["Value"] as string;
197        if (string.IsNullOrEmpty(value) || !(bool)row["IsSelected"])
198          continue;
199        try {
200          Type dataType = (Type)row["DataType"];
201          if (dataType == typeof(int)) {
202            Problem.IntProblemCharacteristicValues.Add(new OKBAdmin.IntProblemCharacteristicValue() {
203              ProblemId = Problem.Id,
204              ProblemCharacteristicId = (int)row["Id"],
205              Value = int.Parse((string)row["Value"], CultureInfo.InvariantCulture.NumberFormat),
206            });
207          } else if (dataType == typeof(double)) {
208            Problem.FloatProblemCharacteristicValues.Add(new OKBAdmin.FloatProblemCharacteristicValue() {
209              ProblemId = Problem.Id,
210              ProblemCharacteristicId = (int)row["Id"],
211              Value = double.Parse((string)row["Value"], CultureInfo.InvariantCulture.NumberFormat),
212            });
213          } else if (dataType == typeof(string)) {
214            Problem.CharProblemCharacteristicValues.Add(new OKBAdmin.CharProblemCharacteristicValue() {
215              ProblemId = Problem.Id,
216              ProblemCharacteristicId = (int)row["Id"],
217              Value = (string)row["Value"],
218            });
219          }
220        } catch (Exception x) {
221          MessageBox.Show(
222            String.Format("Could not create problem characteristic {0} with value {1}:\n{2}",
223            row["Name"], row["Value"], x), Caption, MessageBoxButton.OK, MessageBoxImage.Error);
224        }
225      }
226    }
227
228    private bool ContentHasParameter(OKBAdmin.Parameter p) {
229      return Problem.Problem_Parameters.Any(ap => ap.ParameterId == p.Id);
230    }
231
232    protected void OnViewParameters(object sender, EventArgs args) {
233      if (sender == ParametersButton && Problem != null)
234        EntityEditorSupport.ShowSelector<OKBAdmin.Parameter>(ContentHasParameter, UpdateParameters);
235    }
236
237    private void UpdateParameters(IEnumerable<OKBAdmin.Parameter> parameters) {
238      Problem.Problem_Parameters.Clear();
239      foreach (OKBAdmin.Parameter p in parameters) {
240        Problem.Problem_Parameters.Add(new OKBAdmin.Problem_Parameter() {
241          ProblemId = Problem.Id,
242          ParameterId = p.Id,
243        });
244      }
245    }
246
247    private void OnDownload(object sender, EventArgs args) {
248      PersistenceHacker.Download(OKBData.EntityType.Problem, Problem.Id);
249    }
250
251    private void OnUpload(object sender, EventArgs args) {
252      PersistenceHacker.Upload(OKBData.EntityType.Problem, Problem.Id);
253    }
254
255    #region IView Members
256
257    public string Caption {
258      get { return "Problem Editor"; }
259      set { throw new NotSupportedException(); }
260    }
261
262    public event EventHandler CaptionChanged;
263    public event EventHandler Changed;   
264
265    public virtual void Close() {
266      MainFormManager.GetMainForm<WPFMainFormBase>().CloseView(this);
267      IsShown = false;
268    }
269
270    public void Hide() {
271      MainFormManager.GetMainForm<WPFMainFormBase>().HideView(this);
272      IsShown = false;
273    }
274
275    public bool IsShown { get; protected set; }
276
277    private bool readOnly = false;
278    public bool ReadOnly {
279      get {
280        return readOnly;
281      }
282      set {
283        if (value == readOnly) return;
284        readOnly = value;
285        OnReadOnlyChanged();
286      }
287    }
288    public event EventHandler ReadOnlyChanged;
289    protected void OnReadOnlyChanged() {
290      EventHandler handler = ReadOnlyChanged;
291      if (handler != null)
292        handler(this, EventArgs.Empty);
293    }
294
295    public void Show() {
296      MainFormManager.GetMainForm<WPFMainFormBase>().ShowView(this);
297      IsShown = true;
298    }
299
300    #endregion
301  }
302}
Note: See TracBrowser for help on using the repository browser.