Free cookie consent management tool by TermsFeed Policy Generator

source: branches/OKB/HeuristicLab.Clients.OKB-3.3/OKBClient.cs @ 4896

Last change on this file since 4896 was 4591, checked in by swagner, 14 years ago

Worked on OKB (#1174)

File size: 21.1 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 System.Collections.Generic;
24using System.Linq;
25using HeuristicLab.Clients.Common;
26using HeuristicLab.Collections;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Data;
30using HeuristicLab.Optimization;
31using HeuristicLab.PluginInfrastructure;
32
33namespace HeuristicLab.Clients.OKB {
34  [Item("OKBClient", "Client for accessing the OKB.")]
35  public sealed class OKBClient : IContent {
36    private static OKBClient instance;
37    public static OKBClient Instance {
38      get {
39        if (instance == null) instance = new OKBClient();
40        return instance;
41      }
42    }
43
44    #region Properties
45    private ItemCollection<Platform> platforms;
46    public ItemCollection<Platform> Platforms {
47      get { return platforms; }
48    }
49    private ItemCollection<DataType> dataTypes;
50    public ItemCollection<DataType> DataTypes {
51      get { return dataTypes; }
52    }
53    private IEnumerable<User> users;
54    public IEnumerable<User> Users {
55      get { return users; }
56    }
57    private ItemCollection<AlgorithmClass> algorithmClasses;
58    public ItemCollection<AlgorithmClass> AlgorithmClasses {
59      get { return algorithmClasses; }
60    }
61    private ItemCollection<Algorithm> algorithms;
62    public ItemCollection<Algorithm> Algorithms {
63      get { return algorithms; }
64    }
65    private ItemCollection<ProblemClass> problemClasses;
66    public ItemCollection<ProblemClass> ProblemClasses {
67      get { return problemClasses; }
68    }
69    private ItemCollection<Problem> problems;
70    public ItemCollection<Problem> Problems {
71      get { return problems; }
72    }
73    #endregion
74
75    private OKBClient() {
76      platforms = new ItemCollection<Platform>();
77      platforms.ItemsRemoved += new CollectionItemsChangedEventHandler<Platform>(platforms_ItemsRemoved);
78      dataTypes = new ItemCollection<DataType>();
79      dataTypes.ItemsRemoved += new CollectionItemsChangedEventHandler<DataType>(dataTypes_ItemsRemoved);
80      algorithmClasses = new ItemCollection<AlgorithmClass>();
81      algorithmClasses.ItemsRemoved += new CollectionItemsChangedEventHandler<AlgorithmClass>(algorithmClasses_ItemsRemoved);
82      algorithms = new ItemCollection<Algorithm>();
83      algorithms.ItemsRemoved += new CollectionItemsChangedEventHandler<Algorithm>(algorithms_ItemsRemoved);
84      problemClasses = new ItemCollection<ProblemClass>();
85      problemClasses.ItemsRemoved += new CollectionItemsChangedEventHandler<ProblemClass>(problemClasses_ItemsRemoved);
86      problems = new ItemCollection<Problem>();
87      problems.ItemsRemoved += new CollectionItemsChangedEventHandler<Problem>(problems_ItemsRemoved);
88    }
89
90    #region Refresh
91    public void Refresh() {
92      OnRefreshing();
93
94      platforms.Clear();
95      dataTypes.Clear();
96      algorithmClasses.Clear();
97      algorithms.Clear();
98      problemClasses.Clear();
99      problems.Clear();
100
101      var call = new Func<Exception>(delegate() {
102        try {
103          platforms.AddRange(CallAdminService<Platform[]>(s => s.GetPlatforms()).OrderBy(x => x.Name));
104          dataTypes.AddRange(CallAdminService<DataType[]>(s => s.GetDataTypes()).OrderBy(x => x.Name));
105          users = CallAuthenticationService<User[]>(s => s.GetUsers()).OrderBy(x => x.Name);
106          algorithmClasses.AddRange(CallAdminService<AlgorithmClass[]>(s => s.GetAlgorithmClasses()).OrderBy(x => x.Name));
107          algorithms.AddRange(CallAdminService<Algorithm[]>(s => s.GetAlgorithms()).OrderBy(x => x.Name));
108          problemClasses.AddRange(CallAdminService<ProblemClass[]>(s => s.GetProblemClasses()).OrderBy(x => x.Name));
109          problems.AddRange(CallAdminService<Problem[]>(s => s.GetProblems()).OrderBy(x => x.Name));
110          return null;
111        }
112        catch (Exception ex) {
113          return ex;
114        }
115      });
116      call.BeginInvoke(delegate(IAsyncResult result) {
117        Exception ex = call.EndInvoke(result);
118        if (ex != null) ErrorHandling.ShowErrorDialog("Refresh failed.", ex);
119        OnRefreshed();
120      }, null);
121    }
122    #endregion
123
124    #region Store
125    public bool Store(IOKBItem item) {
126      try {
127        if (item.Id == 0) {
128          if (item is Platform)
129            item.Id = CallAdminService<long>(s => s.AddPlatform((Platform)item));
130          else if (item is DataType)
131            item.Id = CallAdminService<long>(s => s.AddDataType((DataType)item));
132          else if (item is AlgorithmClass)
133            item.Id = CallAdminService<long>(s => s.AddAlgorithmClass((AlgorithmClass)item));
134          else if (item is Algorithm)
135            item.Id = CallAdminService<long>(s => s.AddAlgorithm((Algorithm)item));
136          else if (item is AlgorithmParameter)
137            item.Id = CallAdminService<long>(s => s.AddAlgorithmParameter((AlgorithmParameter)item));
138          else if (item is ProblemClass)
139            item.Id = CallAdminService<long>(s => s.AddProblemClass((ProblemClass)item));
140          else if (item is Problem)
141            item.Id = CallAdminService<long>(s => s.AddProblem((Problem)item));
142          else if (item is ProblemParameter)
143            item.Id = CallAdminService<long>(s => s.AddProblemParameter((ProblemParameter)item));
144          else if (item is Result)
145            item.Id = CallAdminService<long>(s => s.AddResult((Result)item));
146          else if (item is Experiment)
147            item.Id = CallAdminService<long>(s => s.AddExperiment((Experiment)item));
148          else if (item is Run)
149            item.Id = CallAdminService<long>(s => s.AddRun((Run)item));
150        } else {
151          if (item is Platform)
152            CallAdminService(s => s.UpdatePlatform((Platform)item));
153          else if (item is DataType)
154            CallAdminService(s => s.UpdateDataType((DataType)item));
155          else if (item is AlgorithmClass)
156            CallAdminService(s => s.UpdateAlgorithmClass((AlgorithmClass)item));
157          else if (item is Algorithm)
158            CallAdminService(s => s.UpdateAlgorithm((Algorithm)item));
159          else if (item is AlgorithmParameter)
160            CallAdminService(s => s.UpdateAlgorithmParameter((AlgorithmParameter)item));
161          else if (item is ProblemClass)
162            CallAdminService(s => s.UpdateProblemClass((ProblemClass)item));
163          else if (item is Problem)
164            CallAdminService(s => s.UpdateProblem((Problem)item));
165          else if (item is ProblemParameter)
166            CallAdminService(s => s.UpdateProblemParameter((ProblemParameter)item));
167          else if (item is Result)
168            CallAdminService(s => s.UpdateResult((Result)item));
169          else if (item is Experiment)
170            item.Id = CallAdminService<long>(s => s.AddExperiment((Experiment)item));
171          else if (item is Run)
172            item.Id = CallAdminService<long>(s => s.AddRun((Run)item));
173        }
174        return true;
175      }
176      catch (Exception ex) {
177        ErrorHandling.ShowErrorDialog("Store failed.", ex);
178        return false;
179      }
180    }
181    #endregion
182
183    #region DataType Methods
184    public DataType ConvertToDataType(Type type) {
185      DataType dataType = DataTypes.FirstOrDefault(x => x.Name == type.AssemblyQualifiedName);
186      if (dataType == null) {
187        dataType = new DataType();
188        dataType.Name = type.AssemblyQualifiedName;
189        dataType.PlatformId = Platforms.FirstOrDefault(x => x.Name == "HeuristicLab 3.3").Id;
190
191        if (typeof(BoolValue).IsAssignableFrom(type))
192          dataType.SqlName = "bit";
193        else if (typeof(IntValue).IsAssignableFrom(type))
194          dataType.SqlName = "bigint";
195        else if (typeof(DoubleValue).IsAssignableFrom(type))
196          dataType.SqlName = "float";
197        else if (typeof(StringValue).IsAssignableFrom(type) || typeof(IStringConvertibleValue).IsAssignableFrom(type))
198          dataType.SqlName = "nvarchar";
199        else
200          dataType.SqlName = "varbinary";
201
202        dataType.Store();
203        DataTypes.Add(dataType);
204      }
205      return dataType;
206    }
207    #endregion
208
209    #region Algorithm Methods
210    public Guid[] GetAlgorithmUsers(long algorithmId) {
211      try {
212        return CallAdminService<Guid[]>(s => s.GetAlgorithmUsers(algorithmId));
213      }
214      catch (Exception ex) {
215        ErrorHandling.ShowErrorDialog("Refresh authorized algorithm users failed.", ex);
216        return null;
217      }
218    }
219    public bool UpdateAlgorithmUsers(long algorithmId, Guid[] users) {
220      try {
221        CallAdminService(s => s.UpdateAlgorithmUsers(algorithmId, users));
222        return true;
223      }
224      catch (Exception ex) {
225        ErrorHandling.ShowErrorDialog("Update authorized algorithm users failed.", ex);
226        return false;
227      }
228    }
229    public AlgorithmData GetAlgorithmData(long algorithmId) {
230      try {
231        return CallAdminService<AlgorithmData>(s => s.GetAlgorithmData(algorithmId));
232      }
233      catch (Exception ex) {
234        ErrorHandling.ShowErrorDialog("Refresh algorithm data failed.", ex);
235        return null;
236      }
237    }
238    public bool UpdateAlgorithmData(AlgorithmData algorithmData) {
239      try {
240        CallAdminService(s => s.UpdateAlgorithmData(algorithmData));
241        return true;
242      }
243      catch (Exception ex) {
244        ErrorHandling.ShowErrorDialog("Update algorithm data failed.", ex);
245        return false;
246      }
247    }
248    public ItemCollection<AlgorithmParameter> GetAlgorithmParameters(long algorithmId) {
249      try {
250        ItemCollection<AlgorithmParameter> parameters = new ItemCollection<AlgorithmParameter>();
251        parameters.AddRange(CallAdminService<AlgorithmParameter[]>(s => s.GetAlgorithmParameters(algorithmId)).OrderBy(x => x.Name));
252        return parameters;
253      }
254      catch (Exception ex) {
255        ErrorHandling.ShowErrorDialog("Refresh algorithm parameters failed.", ex);
256        return null;
257      }
258    }
259    public ItemCollection<Result> GetResults(long algorithmId) {
260      try {
261        ItemCollection<Result> results = new ItemCollection<Result>();
262        results.AddRange(CallAdminService<Result[]>(s => s.GetResults(algorithmId)).OrderBy(x => x.Name));
263        return results;
264      }
265      catch (Exception ex) {
266        ErrorHandling.ShowErrorDialog("Refresh results failed.", ex);
267        return null;
268      }
269    }
270    #endregion
271
272    #region Problem Methods
273    public Guid[] GetProblemUsers(long problemId) {
274      try {
275        return CallAdminService<Guid[]>(s => s.GetProblemUsers(problemId));
276      }
277      catch (Exception ex) {
278        ErrorHandling.ShowErrorDialog("Refresh authorized problem users failed.", ex);
279        return null;
280      }
281    }
282    public bool UpdateProblemUsers(long problemId, Guid[] users) {
283      try {
284        CallAdminService(s => s.UpdateProblemUsers(problemId, users));
285        return true;
286      }
287      catch (Exception ex) {
288        ErrorHandling.ShowErrorDialog("Update authorized problem users failed.", ex);
289        return false;
290      }
291    }
292    public ProblemData GetProblemData(long problemId) {
293      try {
294        return CallAdminService<ProblemData>(s => s.GetProblemData(problemId));
295      }
296      catch (Exception ex) {
297        ErrorHandling.ShowErrorDialog("Refresh problem data failed.", ex);
298        return null;
299      }
300    }
301    public bool UpdateProblemData(ProblemData problemData) {
302      try {
303        CallAdminService(s => s.UpdateProblemData(problemData));
304        return true;
305      }
306      catch (Exception ex) {
307        ErrorHandling.ShowErrorDialog("Update problem data failed.", ex);
308        return false;
309      }
310    }
311    public ItemCollection<ProblemParameter> GetProblemParameters(long problemId) {
312      try {
313        ItemCollection<ProblemParameter> parameters = new ItemCollection<ProblemParameter>();
314        parameters.AddRange(CallAdminService<ProblemParameter[]>(s => s.GetProblemParameters(problemId)).OrderBy(x => x.Name));
315        return parameters;
316      }
317      catch (Exception ex) {
318        ErrorHandling.ShowErrorDialog("Refresh problem parameters failed.", ex);
319        return null;
320      }
321    }
322    #endregion
323
324    #region Run Methods
325    public bool AddRun(long algorithmId, long problemId, HeuristicLab.Optimization.Run run) {
326      try {
327        IAlgorithm algorithm = run.Algorithm;
328        IProblem problem = algorithm.Problem;
329
330        ItemCollection<AlgorithmParameter> algorithmParameters = GetAlgorithmParameters(algorithmId);
331        List<AlgorithmParameterValue> algorithmParameterValues = CollectAlgorithmParameterValues(algorithmId, algorithmParameters, algorithm, "");
332        ItemCollection<ProblemParameter> problemParameters = GetProblemParameters(problemId);
333        List<ProblemParameterValue> problemParameterValues = CollectProblemParamterValues(problemId, problemParameters, problem, "");
334        ItemCollection<Result> results = GetResults(algorithmId);
335        List<ResultValue> resultValues = CollectResultValues(algorithmId, results, algorithm);
336
337        Experiment exp = new Experiment();
338        exp.AlgorithmId = algorithmId;
339        exp.ProblemId = problemId;
340        exp.AlgorithmParameterValues = algorithmParameterValues.ToArray();
341        exp.ProblemParameterValues = problemParameterValues.ToArray();
342        exp.Store();
343
344        Run r = new Run();
345        r.ExperimentId = exp.Id;
346        r.ClientId = Guid.NewGuid();
347        r.FinishedDate = DateTime.Now;
348        r.RandomSeed = ((IntValue)((IValueParameter)run.Parameters["Seed"]).Value).Value;
349        r.ResultValues = resultValues.ToArray();
350        r.Store();
351
352        return true;
353      }
354      catch (Exception ex) {
355        ErrorHandling.ShowErrorDialog("Store run failed.", ex);
356        return false;
357      }
358    }
359
360    private List<AlgorithmParameterValue> CollectAlgorithmParameterValues(long algorithmId, ItemCollection<AlgorithmParameter> parameters, IParameterizedItem item, string prefix) {
361      List<AlgorithmParameterValue> values = new List<AlgorithmParameterValue>();
362      foreach (IValueParameter param in item.Parameters.OfType<IValueParameter>()) {
363        if (param.GetsCollected && (param.Value != null)) {
364          AlgorithmParameter p = parameters.FirstOrDefault(x => x.Name == prefix + param.Name);
365          if (p == null) {
366            p = new AlgorithmParameter();
367            p.Name = prefix + param.Name;
368            p.Alias = prefix + param.Name;
369            p.Description = param.Description;
370            p.AlgorithmId = algorithmId;
371            p.DataTypeId = ConvertToDataType(param.DataType).Id;
372            p.Store();
373            parameters.Add(p);
374          }
375          AlgorithmParameterValue value = null;
376          // TODO
377          value.AlgorithmParameterId = p.Id;
378          value.DataTypeId = ConvertToDataType(param.Value.GetType()).Id;
379        }
380
381        if (param.Value is IParameterizedItem)
382          values.AddRange(CollectAlgorithmParameterValues(algorithmId, parameters, (IParameterizedItem)param.Value, (string.IsNullOrEmpty(prefix) ? param.Name : prefix + param.Name) + "."));
383      }
384      return values;
385    }
386    private List<ProblemParameterValue> CollectProblemParamterValues(long problemId, ItemCollection<ProblemParameter> parameters, IParameterizedItem item, string prefix) {
387      List<ProblemParameterValue> values = new List<ProblemParameterValue>();
388      foreach (IValueParameter param in item.Parameters.OfType<IValueParameter>()) {
389        if (param.GetsCollected && (param.Value != null) && (parameters.FirstOrDefault(x => x.Name == prefix + param.Name) == null)) {
390          ProblemParameter p = new ProblemParameter();
391          p.Name = prefix + param.Name;
392          p.Alias = prefix + param.Name;
393          p.Description = param.Description;
394          p.ProblemId = problemId;
395          p.DataTypeId = ConvertToDataType(param.DataType).Id;
396          p.Store();
397          parameters.Add(p);
398        }
399        if (param.Value is IParameterizedItem)
400          values.AddRange(CollectProblemParamterValues(problemId, parameters, (IParameterizedItem)param.Value, (string.IsNullOrEmpty(prefix) ? param.Name : prefix + param.Name) + "."));
401      }
402      return values;
403    }
404    private List<ResultValue> CollectResultValues(long algorithmId, ItemCollection<Result> results, IAlgorithm algorithm) {
405      List<ResultValue> values = new List<ResultValue>();
406      foreach (IResult result in algorithm.Results) {
407        if ((result.Value != null) && (results.FirstOrDefault(x => x.Name == result.Name) == null)) {
408          Result r = new Result();
409          r.Name = result.Name;
410          r.Alias = result.Name;
411          r.Description = result.Description;
412          r.AlgorithmId = algorithmId;
413          r.DataTypeId = ConvertToDataType(result.DataType).Id;
414          r.Store();
415          results.Add(r);
416        }
417      }
418      return values;
419    }
420    #endregion
421
422    #region Events
423    public event EventHandler Refreshing;
424    private void OnRefreshing() {
425      EventHandler handler = Refreshing;
426      if (handler != null) handler(this, EventArgs.Empty);
427    }
428    public event EventHandler Refreshed;
429    private void OnRefreshed() {
430      EventHandler handler = Refreshed;
431      if (handler != null) handler(this, EventArgs.Empty);
432    }
433
434    private void platforms_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<Platform> e) {
435      try {
436        foreach (Platform p in e.Items)
437          CallAdminService(s => s.DeletePlatform(p.Id));
438      }
439      catch (Exception ex) {
440        ErrorHandling.ShowErrorDialog("Delete failed.", ex);
441      }
442    }
443    private void dataTypes_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<DataType> e) {
444      try {
445        foreach (DataType d in e.Items)
446          CallAdminService(s => s.DeleteDataType(d.Id));
447      }
448      catch (Exception ex) {
449        ErrorHandling.ShowErrorDialog("Delete failed.", ex);
450      }
451    }
452    private void algorithmClasses_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<AlgorithmClass> e) {
453      try {
454        foreach (AlgorithmClass a in e.Items)
455          CallAdminService(s => s.DeleteAlgorithmClass(a.Id));
456      }
457      catch (Exception ex) {
458        ErrorHandling.ShowErrorDialog("Delete failed.", ex);
459      }
460    }
461    private void algorithms_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<Algorithm> e) {
462      try {
463        foreach (Algorithm a in e.Items)
464          CallAdminService(s => s.DeleteAlgorithm(a.Id));
465      }
466      catch (Exception ex) {
467        ErrorHandling.ShowErrorDialog("Delete failed.", ex);
468      }
469    }
470    private void problemClasses_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<ProblemClass> e) {
471      try {
472        foreach (ProblemClass p in e.Items)
473          CallAdminService(s => s.DeleteProblemClass(p.Id));
474      }
475      catch (Exception ex) {
476        ErrorHandling.ShowErrorDialog("Delete failed.", ex);
477      }
478    }
479    private void problems_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<Problem> e) {
480      try {
481        foreach (Problem p in e.Items)
482          CallAdminService(s => s.DeleteProblem(p.Id));
483      }
484      catch (Exception ex) {
485        ErrorHandling.ShowErrorDialog("Delete failed.", ex);
486      }
487    }
488    #endregion
489
490    #region Helpers
491    private void CallAdminService(Action<IOKBService> call) {
492      OKBServiceClient client = ClientFactory.CreateClient<OKBServiceClient, IOKBService>();
493      try {
494        call(client);
495      }
496      finally {
497        try {
498          client.Close();
499        }
500        catch (Exception) {
501          client.Abort();
502        }
503      }
504    }
505    private T CallAdminService<T>(Func<IOKBService, T> call) {
506      OKBServiceClient client = ClientFactory.CreateClient<OKBServiceClient, IOKBService>();
507      try {
508        return call(client);
509      }
510      finally {
511        try {
512          client.Close();
513        }
514        catch (Exception) {
515          client.Abort();
516        }
517      }
518    }
519    private T CallAuthenticationService<T>(Func<IAuthenticationService, T> call) {
520      AuthenticationServiceClient client = ClientFactory.CreateClient<AuthenticationServiceClient, IAuthenticationService>();
521      try {
522        return call(client);
523      }
524      finally {
525        try {
526          client.Close();
527        }
528        catch (Exception) {
529          client.Abort();
530        }
531      }
532    }
533    #endregion
534  }
535}
Note: See TracBrowser for help on using the repository browser.