Free cookie consent management tool by TermsFeed Policy Generator

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

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

Worked on OKB (#1174)

File size: 21.1 KB
RevLine 
[4426]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;
[4466]23using System.Collections.Generic;
[4433]24using System.Linq;
[4426]25using HeuristicLab.Clients.Common;
26using HeuristicLab.Collections;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
[4566]29using HeuristicLab.Data;
[4559]30using HeuristicLab.Optimization;
[4426]31using HeuristicLab.PluginInfrastructure;
32
33namespace HeuristicLab.Clients.OKB {
[4549]34  [Item("OKBClient", "Client for accessing the OKB.")]
35  public sealed class OKBClient : IContent {
36    private static OKBClient instance;
37    public static OKBClient Instance {
[4433]38      get {
[4549]39        if (instance == null) instance = new OKBClient();
[4433]40        return instance;
41      }
42    }
43
[4481]44    #region Properties
[4441]45    private ItemCollection<Platform> platforms;
46    public ItemCollection<Platform> Platforms {
47      get { return platforms; }
48    }
[4481]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    }
[4426]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    }
[4481]65    private ItemCollection<ProblemClass> problemClasses;
66    public ItemCollection<ProblemClass> ProblemClasses {
67      get { return problemClasses; }
[4466]68    }
[4481]69    private ItemCollection<Problem> problems;
70    public ItemCollection<Problem> Problems {
71      get { return problems; }
[4466]72    }
[4481]73    #endregion
[4426]74
[4549]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    }
[4426]89
[4481]90    #region Refresh
[4433]91    public void Refresh() {
92      OnRefreshing();
[4549]93
[4441]94      platforms.Clear();
[4481]95      dataTypes.Clear();
[4441]96      algorithmClasses.Clear();
[4433]97      algorithms.Clear();
[4481]98      problemClasses.Clear();
99      problems.Clear();
[4433]100
[4441]101      var call = new Func<Exception>(delegate() {
102        try {
[4466]103          platforms.AddRange(CallAdminService<Platform[]>(s => s.GetPlatforms()).OrderBy(x => x.Name));
[4481]104          dataTypes.AddRange(CallAdminService<DataType[]>(s => s.GetDataTypes()).OrderBy(x => x.Name));
105          users = CallAuthenticationService<User[]>(s => s.GetUsers()).OrderBy(x => x.Name);
[4466]106          algorithmClasses.AddRange(CallAdminService<AlgorithmClass[]>(s => s.GetAlgorithmClasses()).OrderBy(x => x.Name));
107          algorithms.AddRange(CallAdminService<Algorithm[]>(s => s.GetAlgorithms()).OrderBy(x => x.Name));
[4481]108          problemClasses.AddRange(CallAdminService<ProblemClass[]>(s => s.GetProblemClasses()).OrderBy(x => x.Name));
109          problems.AddRange(CallAdminService<Problem[]>(s => s.GetProblems()).OrderBy(x => x.Name));
[4441]110          return null;
111        }
112        catch (Exception ex) {
113          return ex;
114        }
[4433]115      });
[4441]116      call.BeginInvoke(delegate(IAsyncResult result) {
117        Exception ex = call.EndInvoke(result);
118        if (ex != null) ErrorHandling.ShowErrorDialog("Refresh failed.", ex);
[4433]119        OnRefreshed();
120      }, null);
[4426]121    }
[4481]122    #endregion
[4426]123
[4481]124    #region Store
[4441]125    public bool Store(IOKBItem item) {
126      try {
[4481]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));
[4566]136          else if (item is AlgorithmParameter)
137            item.Id = CallAdminService<long>(s => s.AddAlgorithmParameter((AlgorithmParameter)item));
[4481]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));
[4566]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));
[4591]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));
[4481]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));
[4566]159          else if (item is AlgorithmParameter)
160            CallAdminService(s => s.UpdateAlgorithmParameter((AlgorithmParameter)item));
[4481]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));
[4566]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));
[4591]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));
[4481]173        }
[4441]174        return true;
175      }
176      catch (Exception ex) {
177        ErrorHandling.ShowErrorDialog("Store failed.", ex);
178        return false;
179      }
[4433]180    }
[4587]181    #endregion
[4566]182
[4587]183    #region DataType Methods
184    public DataType ConvertToDataType(Type type) {
[4566]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    }
[4481]207    #endregion
[4433]208
[4481]209    #region Algorithm Methods
[4466]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    }
[4481]219    public bool UpdateAlgorithmUsers(long algorithmId, Guid[] users) {
[4466]220      try {
[4481]221        CallAdminService(s => s.UpdateAlgorithmUsers(algorithmId, users));
[4466]222        return true;
223      }
224      catch (Exception ex) {
[4481]225        ErrorHandling.ShowErrorDialog("Update authorized algorithm users failed.", ex);
[4466]226        return false;
227      }
228    }
[4481]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    }
[4566]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    }
[4481]270    #endregion
[4466]271
[4481]272    #region Problem Methods
273    public Guid[] GetProblemUsers(long problemId) {
[4466]274      try {
[4481]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));
[4466]285        return true;
286      }
287      catch (Exception ex) {
[4481]288        ErrorHandling.ShowErrorDialog("Update authorized problem users failed.", ex);
[4466]289        return false;
290      }
291    }
[4481]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    }
[4566]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    }
[4481]322    #endregion
[4466]323
[4587]324    #region Run Methods
[4591]325    public bool AddRun(long algorithmId, long problemId, HeuristicLab.Optimization.Run run) {
[4587]326      try {
327        IAlgorithm algorithm = run.Algorithm;
328        IProblem problem = algorithm.Problem;
329
330        ItemCollection<AlgorithmParameter> algorithmParameters = GetAlgorithmParameters(algorithmId);
[4591]331        List<AlgorithmParameterValue> algorithmParameterValues = CollectAlgorithmParameterValues(algorithmId, algorithmParameters, algorithm, "");
[4587]332        ItemCollection<ProblemParameter> problemParameters = GetProblemParameters(problemId);
[4591]333        List<ProblemParameterValue> problemParameterValues = CollectProblemParamterValues(problemId, problemParameters, problem, "");
334        ItemCollection<Result> results = GetResults(algorithmId);
335        List<ResultValue> resultValues = CollectResultValues(algorithmId, results, algorithm);
[4587]336
[4591]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
[4587]352        return true;
353      }
354      catch (Exception ex) {
355        ErrorHandling.ShowErrorDialog("Store run failed.", ex);
356        return false;
357      }
358    }
359
[4591]360    private List<AlgorithmParameterValue> CollectAlgorithmParameterValues(long algorithmId, ItemCollection<AlgorithmParameter> parameters, IParameterizedItem item, string prefix) {
361      List<AlgorithmParameterValue> values = new List<AlgorithmParameterValue>();
[4587]362      foreach (IValueParameter param in item.Parameters.OfType<IValueParameter>()) {
[4591]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;
[4587]379        }
[4591]380
[4587]381        if (param.Value is IParameterizedItem)
[4591]382          values.AddRange(CollectAlgorithmParameterValues(algorithmId, parameters, (IParameterizedItem)param.Value, (string.IsNullOrEmpty(prefix) ? param.Name : prefix + param.Name) + "."));
[4587]383      }
[4591]384      return values;
[4587]385    }
[4591]386    private List<ProblemParameterValue> CollectProblemParamterValues(long problemId, ItemCollection<ProblemParameter> parameters, IParameterizedItem item, string prefix) {
387      List<ProblemParameterValue> values = new List<ProblemParameterValue>();
[4587]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)
[4591]400          values.AddRange(CollectProblemParamterValues(problemId, parameters, (IParameterizedItem)param.Value, (string.IsNullOrEmpty(prefix) ? param.Name : prefix + param.Name) + "."));
[4587]401      }
[4591]402      return values;
[4587]403    }
[4591]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    }
[4587]420    #endregion
421
[4481]422    #region Events
[4433]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
[4441]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    }
[4481]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    }
[4433]452    private void algorithmClasses_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<AlgorithmClass> e) {
[4441]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      }
[4433]460    }
461    private void algorithms_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<Algorithm> e) {
[4441]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      }
[4433]469    }
[4481]470    private void problemClasses_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<ProblemClass> e) {
[4466]471      try {
[4481]472        foreach (ProblemClass p in e.Items)
473          CallAdminService(s => s.DeleteProblemClass(p.Id));
[4466]474      }
475      catch (Exception ex) {
476        ErrorHandling.ShowErrorDialog("Delete failed.", ex);
477      }
478    }
[4481]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
[4433]489
490    #region Helpers
[4548]491    private void CallAdminService(Action<IOKBService> call) {
492      OKBServiceClient client = ClientFactory.CreateClient<OKBServiceClient, IOKBService>();
[4433]493      try {
494        call(client);
495      }
496      finally {
[4426]497        try {
[4433]498          client.Close();
[4426]499        }
[4433]500        catch (Exception) {
501          client.Abort();
[4426]502        }
503      }
504    }
[4548]505    private T CallAdminService<T>(Func<IOKBService, T> call) {
506      OKBServiceClient client = ClientFactory.CreateClient<OKBServiceClient, IOKBService>();
[4433]507      try {
508        return call(client);
[4426]509      }
[4433]510      finally {
511        try {
512          client.Close();
513        }
514        catch (Exception) {
515          client.Abort();
516        }
517      }
[4426]518    }
[4481]519    private T CallAuthenticationService<T>(Func<IAuthenticationService, T> call) {
[4466]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    }
[4433]533    #endregion
[4426]534  }
535}
Note: See TracBrowser for help on using the repository browser.