Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Clients.Hive.JobManager/3.3/Views/RefreshableHiveJobView.cs @ 17357

Last change on this file since 17357 was 17246, checked in by gkronber, 5 years ago

#2925: merged r17037:17242 from trunk to branch

File size: 30.3 KB
RevLine 
[6976]1#region License Information
2/* HeuristicLab
[17246]3 * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[6976]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.ComponentModel;
24using System.Linq;
25using System.Threading;
[7162]26using System.Threading.Tasks;
[6976]27using System.Windows.Forms;
28using HeuristicLab.Collections;
29using HeuristicLab.Common;
30using HeuristicLab.Core;
31using HeuristicLab.MainForm;
[7582]32using HeuristicLab.MainForm.WindowsForms;
[6976]33using HeuristicLab.Optimization;
34using HeuristicLab.PluginInfrastructure;
[16386]35using System.Collections.Generic;
[6976]36
37namespace HeuristicLab.Clients.Hive.JobManager.Views {
38  /// <summary>
39  /// The base class for visual representations of items.
40  /// </summary>
41  [View("Hive Job View")]
42  [Content(typeof(RefreshableJob), true)]
43  public partial class RefreshableHiveJobView : HeuristicLab.Core.Views.ItemView {
[7910]44    private HiveResourceSelectorDialog hiveResourceSelectorDialog;
[8914]45    private bool SuppressEvents { get; set; }
[8994]46    private object runCollectionViewLocker = new object();
[16386]47    private Project selectedProject;
48    private Dictionary<Guid, Guid> originalJobProjectAssignment = new Dictionary<Guid, Guid>();
[6976]49
50    public new RefreshableJob Content {
51      get { return (RefreshableJob)base.Content; }
[16386]52      set {
53        base.Content = value;
54      }
[6976]55    }
56
57    /// <summary>
58    /// Initializes a new instance of <see cref="ItemBaseView"/>.
59    /// </summary>
60    public RefreshableHiveJobView() {
61      InitializeComponent();
62    }
63
64    protected override void RegisterContentEvents() {
65      base.RegisterContentEvents();
66      Content.RefreshAutomaticallyChanged += new EventHandler(Content_RefreshAutomaticallyChanged);
67      Content.JobChanged += new EventHandler(Content_HiveExperimentChanged);
68      Content.IsControllableChanged += new EventHandler(Content_IsControllableChanged);
69      Content.JobStatisticsChanged += new EventHandler(Content_JobStatisticsChanged);
70      Content.ExceptionOccured += new EventHandler<EventArgs<Exception>>(Content_ExceptionOccured);
71      Content.StateLogListChanged += new EventHandler(Content_StateLogListChanged);
72      Content.HiveTasksChanged += new EventHandler(Content_HiveTasksChanged);
73      Content.ExecutionStateChanged += new EventHandler(Content_ExecutionStateChanged);
74      Content.ExecutionTimeChanged += new EventHandler(Content_ExecutionTimeChanged);
75      Content.Loaded += new EventHandler(Content_Loaded);
[7782]76      Content.TaskReceived += new EventHandler(Content_TaskReceived);
[16662]77      Progress.Show(this, Content.Progress);
[6976]78    }
79
80    protected override void DeregisterContentEvents() {
81      Content.RefreshAutomaticallyChanged -= new EventHandler(Content_RefreshAutomaticallyChanged);
82      Content.JobChanged -= new EventHandler(Content_HiveExperimentChanged);
83      Content.IsControllableChanged -= new EventHandler(Content_IsControllableChanged);
84      Content.JobStatisticsChanged -= new EventHandler(Content_JobStatisticsChanged);
85      Content.ExceptionOccured -= new EventHandler<EventArgs<Exception>>(Content_ExceptionOccured);
86      Content.StateLogListChanged -= new EventHandler(Content_StateLogListChanged);
87      Content.HiveTasksChanged -= new EventHandler(Content_HiveTasksChanged);
88      Content.ExecutionStateChanged -= new EventHandler(Content_ExecutionStateChanged);
89      Content.ExecutionTimeChanged -= new EventHandler(Content_ExecutionTimeChanged);
90      Content.Loaded -= new EventHandler(Content_Loaded);
[7782]91      Content.TaskReceived -= new EventHandler(Content_TaskReceived);
[16662]92      Progress.Hide(this, false);
[9219]93      DeregisterHiveExperimentEvents();
94      DeregisterHiveTasksEvents();
[6976]95      base.DeregisterContentEvents();
96    }
97
98    private void RegisterHiveExperimentEvents() {
99      Content.Job.PropertyChanged += new PropertyChangedEventHandler(HiveExperiment_PropertyChanged);
100    }
101
102    private void DeregisterHiveExperimentEvents() {
103      Content.Job.PropertyChanged -= new PropertyChangedEventHandler(HiveExperiment_PropertyChanged);
104    }
105
[9219]106    private void RegisterHiveTasksEvents() {
[6976]107      Content.HiveTasks.ItemsAdded += new CollectionItemsChangedEventHandler<HiveTask>(HiveTasks_ItemsAdded);
108      Content.HiveTasks.ItemsRemoved += new CollectionItemsChangedEventHandler<HiveTask>(HiveTasks_ItemsRemoved);
109      Content.HiveTasks.CollectionReset += new CollectionItemsChangedEventHandler<HiveTask>(HiveTasks_CollectionReset);
110    }
[9219]111    private void DeregisterHiveTasksEvents() {
[6976]112      Content.HiveTasks.ItemsAdded -= new CollectionItemsChangedEventHandler<HiveTask>(HiveTasks_ItemsAdded);
113      Content.HiveTasks.ItemsRemoved -= new CollectionItemsChangedEventHandler<HiveTask>(HiveTasks_ItemsRemoved);
114      Content.HiveTasks.CollectionReset -= new CollectionItemsChangedEventHandler<HiveTask>(HiveTasks_CollectionReset);
115    }
116
117    protected override void OnContentChanged() {
118      base.OnContentChanged();
[8914]119      SuppressEvents = true;
120      try {
121        if (Content == null) {
122          nameTextBox.Text = string.Empty;
[16386]123          descriptionTextBox.Text = string.Empty;
[8914]124          executionTimeTextBox.Text = string.Empty;
[16386]125          projectNameTextBox.Text = string.Empty;
[8914]126          refreshAutomaticallyCheckBox.Checked = false;
[8994]127          lock (runCollectionViewLocker) {
128            runCollectionViewHost.Content = null;
129          }
[9219]130          logView.Content = null;
131          jobsTreeView.Content = null;
132          hiveExperimentPermissionListView.Content = null;
133          stateLogViewHost.Content = null;
[8914]134        } else {
[16662]135          if (Content.Job != null
136            && Content.Job.Id != Guid.Empty
[16386]137            && !originalJobProjectAssignment.ContainsKey(Content.Job.Id)) {
138            originalJobProjectAssignment.Add(Content.Job.Id, Content.Job.ProjectId);
139          }
140
141          // project look up
142          if (Content.Job != null && Content.Job.ProjectId == Guid.Empty) {
143            projectNameTextBox.Text = string.Empty;
144            if (HiveClient.Instance != null && HiveClient.Instance.Projects != null && HiveClient.Instance.Projects.Count == 1) {
145              var p = HiveClient.Instance.Projects.FirstOrDefault();
146              if (p != null && p.Id != Guid.Empty) {
147                hiveResourceSelectorDialog = new HiveResourceSelectorDialog(Content.Job.Id, Content.Job.ProjectId);
148                Content.Job.ProjectId = p.Id;
149                var resources = HiveClient.Instance.GetAvailableResourcesForProject(p.Id).ToList();
150                Content.Job.ResourceIds = resources.Select(x => x.Id).ToList();
151                hiveResourceSelectorDialog.SelectedProjectId = Content.Job.ProjectId;
152                hiveResourceSelectorDialog.SelectedResourceIds = Content.Job.ResourceIds;
153
154                var cores = resources.Union(resources.SelectMany(x => HiveClient.Instance.GetAvailableResourceDescendants(x.Id)))
155                  .OfType<Slave>()
156                  .Distinct()
157                  .Sum(x => x.Cores);
158
159                projectNameTextBox.Text = HiveClient.Instance.GetProjectAncestry(Content.Job.ProjectId);
160                projectNameTextBox.Text += "   (" + (cores.HasValue ? cores.Value.ToString() : "0") + " cores)";
[16662]161              }
[16386]162            }
163          } else if (Content.Job != null && Content.Job.ProjectId != Guid.Empty) {
164            if (selectedProject == null || selectedProject.Id != Content.Job.ProjectId) {
165              selectedProject = GetProject(Content.Job.ProjectId);
166              hiveResourceSelectorDialog = null;
167            }
168
[16662]169            if (hiveResourceSelectorDialog == null)
[16386]170              hiveResourceSelectorDialog = new HiveResourceSelectorDialog(Content.Job.Id, Content.Job.ProjectId);
171
172            if (selectedProject != null) {
173              projectNameTextBox.Text = HiveClient.Instance.GetProjectAncestry(selectedProject.Id);
174            } else {
175              projectNameTextBox.Text = string.Empty;
176            }
177
178            List<Resource> resources = null;
179            if (Content.Job.ResourceIds == null)
180              resources = HiveClient.Instance.GetAssignedResourcesForJob(Content.Job.Id).ToList();
181            else
182              resources = HiveClient.Instance.Resources.Where(x => Content.Job.ResourceIds.Contains(x.Id)).ToList();
183
184            Content.Job.ResourceIds = resources.Select(x => x.Id).ToList();
185            hiveResourceSelectorDialog.SelectedResourceIds = Content.Job.ResourceIds;
186
187            var cores = resources.Union(resources.SelectMany(x => HiveClient.Instance.GetAvailableResourceDescendants(x.Id)))
188              .OfType<Slave>()
189              .Distinct()
190              .Sum(x => x.Cores);
191
192            projectNameTextBox.Text += "   (" + (cores.HasValue ? cores.Value.ToString() : "0") + " cores)";
193
194          } else {
195            selectedProject = null;
196            projectNameTextBox.Text = string.Empty;
197            Content.Job.ResourceIds = null;
198          }
199
200
[8914]201          nameTextBox.Text = Content.Job.Name;
[16386]202          descriptionTextBox.Text = Content.Job.Description;
[8914]203          executionTimeTextBox.Text = Content.ExecutionTime.ToString();
204          refreshAutomaticallyCheckBox.Checked = Content.RefreshAutomatically;
[16662]205
[8914]206          logView.Content = Content.Log;
[8994]207          lock (runCollectionViewLocker) {
208            runCollectionViewHost.Content = GetAllRunsFromJob(Content);
209          }
[8914]210        }
[16386]211      } finally {
[8914]212        SuppressEvents = false;
213      }
[16386]214      hiveExperimentPermissionListView.Content = null; // has to be filled by refresh
[6976]215      Content_JobStatisticsChanged(this, EventArgs.Empty);
216      Content_HiveExperimentChanged(this, EventArgs.Empty);
217      Content_HiveTasksChanged(this, EventArgs.Empty);
218      Content_StateLogListChanged(this, EventArgs.Empty);
219      HiveExperiment_PropertyChanged(this, new PropertyChangedEventArgs("Id"));
220      SetEnabledStateOfControls();
221    }
222
[9223]223    protected override void OnLockedChanged() {
224      base.OnLockedChanged();
225      executionTimeTextBox.Enabled = !Locked;
226      jobsTextBox.Enabled = !Locked;
227      calculatingTextBox.Enabled = !Locked;
228      finishedTextBox.Enabled = !Locked;
229      tabControl.Enabled = !Locked;
230      nameTextBox.Enabled = !Locked;
[16386]231      descriptionTextBox.Enabled = !Locked;
232      projectNameTextBox.Enabled = !Locked;
[9223]233      searchButton.Enabled = !Locked;
234      jobsTreeView.Enabled = !Locked;
235      refreshAutomaticallyCheckBox.Enabled = !Locked;
236      refreshButton.Enabled = !Locked;
237      UnloadButton.Enabled = !Locked;
238      startButton.Enabled = !Locked;
239      pauseButton.Enabled = !Locked;
240      stopButton.Enabled = !Locked;
241    }
242
[6976]243    protected override void SetEnabledStateOfControls() {
244      base.SetEnabledStateOfControls();
[9223]245      if (!Locked) {
246        executionTimeTextBox.Enabled = Content != null;
247        jobsTextBox.ReadOnly = true;
248        calculatingTextBox.ReadOnly = true;
249        finishedTextBox.ReadOnly = true;
[6976]250
[9223]251        if (Content != null) {
252          bool alreadyUploaded = Content.Id != Guid.Empty;
253          bool jobsLoaded = Content.HiveTasks != null && Content.HiveTasks.All(x => x.Task.Id != Guid.Empty);
254          tabControl.Enabled = !Content.IsProgressing;
[6976]255
[16386]256          this.nameTextBox.ReadOnly = Content.IsProgressing;
257          this.descriptionTextBox.ReadOnly = Content.IsProgressing;
258          this.searchButton.Enabled = !Content.IsProgressing && Content.ExecutionState != ExecutionState.Stopped;
[9223]259          this.jobsTreeView.ReadOnly = !Content.IsControllable || Content.ExecutionState != ExecutionState.Prepared || alreadyUploaded || Content.IsProgressing;
[6976]260
[14901]261          this.refreshAutomaticallyCheckBox.Enabled = Content.IsControllable && alreadyUploaded && jobsLoaded && (Content.ExecutionState == ExecutionState.Started || Content.ExecutionState == ExecutionState.Paused) && !Content.IsProgressing;
[9223]262          this.refreshButton.Enabled = Content.IsDownloadable && alreadyUploaded && !Content.IsProgressing;
[16386]263          this.updateButton.Enabled = Content.ExecutionState != ExecutionState.Prepared && Content.ExecutionState != ExecutionState.Stopped && !Content.IsProgressing;
[9219]264
[9223]265          this.UnloadButton.Enabled = Content.HiveTasks != null && Content.HiveTasks.Count > 0 && alreadyUploaded && !Content.IsProgressing;
266        }
267        SetEnabledStateOfExecutableButtons();
268        tabControl_SelectedIndexChanged(this, EventArgs.Empty); // ensure sharing tabpage is disabled
[6976]269      }
270    }
271
272    protected override void OnClosed(FormClosedEventArgs e) {
273      if (Content != null) {
274        if (Content.RefreshAutomatically)
275          Content.StopResultPolling();
276      }
277      base.OnClosed(e);
278    }
279
280    #region Content Events
[7782]281    void Content_TaskReceived(object sender, EventArgs e) {
[8994]282      lock (runCollectionViewLocker) {
283        runCollectionViewHost.Content = GetAllRunsFromJob(Content);
284      }
[7782]285    }
286
[6976]287    private void HiveTasks_ItemsAdded(object sender, CollectionItemsChangedEventArgs<HiveTask> e) {
288      if (InvokeRequired)
289        Invoke(new CollectionItemsChangedEventHandler<HiveTask>(HiveTasks_ItemsAdded), sender, e);
290      else {
291        SetEnabledStateOfControls();
292      }
293    }
294
295    private void HiveTasks_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<HiveTask> e) {
296      if (InvokeRequired)
297        Invoke(new CollectionItemsChangedEventHandler<HiveTask>(HiveTasks_ItemsRemoved), sender, e);
298      else {
299        SetEnabledStateOfControls();
300      }
301    }
302
303    private void HiveTasks_CollectionReset(object sender, CollectionItemsChangedEventArgs<HiveTask> e) {
304      if (InvokeRequired)
305        Invoke(new CollectionItemsChangedEventHandler<HiveTask>(HiveTasks_CollectionReset), sender, e);
306      else {
307        SetEnabledStateOfControls();
308      }
309    }
310
311    private void Content_ExecutionStateChanged(object sender, EventArgs e) {
312      if (InvokeRequired)
313        Invoke(new EventHandler(Content_ExecutionStateChanged), sender, e);
314      else
315        SetEnabledStateOfControls();
316    }
[9894]317
[6976]318    private void Content_ExecutionTimeChanged(object sender, EventArgs e) {
319      if (InvokeRequired)
320        Invoke(new EventHandler(Content_ExecutionTimeChanged), sender, e);
321      else
322        executionTimeTextBox.Text = Content.ExecutionTime.ToString();
323    }
324    private void Content_RefreshAutomaticallyChanged(object sender, EventArgs e) {
325      if (InvokeRequired)
326        Invoke(new EventHandler(Content_RefreshAutomaticallyChanged), sender, e);
327      else {
328        refreshAutomaticallyCheckBox.Checked = Content.RefreshAutomatically;
329        SetEnabledStateOfControls();
330      }
331    }
332    private void Content_HiveTasksChanged(object sender, EventArgs e) {
333      if (InvokeRequired)
334        Invoke(new EventHandler(Content_HiveTasksChanged), sender, e);
335      else {
336        if (Content != null && Content.HiveTasks != null) {
337          jobsTreeView.Content = Content.HiveTasks;
[9219]338          RegisterHiveTasksEvents();
[6976]339        } else {
340          jobsTreeView.Content = null;
341        }
342        SetEnabledStateOfControls();
343      }
344    }
345
346    void Content_Loaded(object sender, EventArgs e) {
[8994]347      lock (runCollectionViewLocker) {
348        runCollectionViewHost.Content = GetAllRunsFromJob(Content);
349      }
[6976]350    }
351
352    private void Content_HiveExperimentChanged(object sender, EventArgs e) {
353      if (Content != null && Content.Job != null) {
354        RegisterHiveExperimentEvents();
355      }
356    }
357    private void Content_IsControllableChanged(object sender, EventArgs e) {
358      SetEnabledStateOfControls();
359    }
360    private void Content_JobStatisticsChanged(object sender, EventArgs e) {
361      if (InvokeRequired)
362        Invoke(new EventHandler(Content_JobStatisticsChanged), sender, e);
363      else {
364        if (Content != null) {
365          jobsTextBox.Text = (Content.Job.JobCount - Content.Job.CalculatingCount - Content.Job.FinishedCount).ToString();
366          calculatingTextBox.Text = Content.Job.CalculatingCount.ToString();
367          finishedTextBox.Text = Content.Job.FinishedCount.ToString();
368        } else {
369          jobsTextBox.Text = "0";
370          calculatingTextBox.Text = "0";
371          finishedTextBox.Text = "0";
372        }
373      }
374    }
375    private void Content_ExceptionOccured(object sender, EventArgs<Exception> e) {
[7409]376      if (InvokeRequired)
377        Invoke(new EventHandler<EventArgs<Exception>>(Content_ExceptionOccured), sender, e);
378      else {
379        //don't show the error dialog when downloading tasks, the HiveClient will throw an exception and the dialog will be shown then
380        if (sender.GetType() != typeof(ConcurrentTaskDownloader<ItemTask>) && sender.GetType() != typeof(TaskDownloader)) {
381          ErrorHandling.ShowErrorDialog(this, e.Value);
382        }
383      }
[6976]384    }
385    private void Content_StateLogListChanged(object sender, EventArgs e) {
386      if (InvokeRequired)
387        Invoke(new EventHandler(Content_StateLogListChanged), sender, e);
388      else {
389        UpdateStateLogList();
390      }
391    }
392
393    private void UpdateStateLogList() {
394      if (Content != null && this.Content.Job != null) {
395        stateLogViewHost.Content = this.Content.StateLogList;
396      } else {
397        stateLogViewHost.Content = null;
398      }
399    }
400
401    private void HiveExperiment_PropertyChanged(object sender, PropertyChangedEventArgs e) {
402      if (this.Content != null && e.PropertyName == "Id") this.hiveExperimentPermissionListView.HiveExperimentId = this.Content.Job.Id;
403    }
404    #endregion
405
406    #region Control events
[7910]407    private void searchButton_Click(object sender, EventArgs e) {
[16386]408      if (hiveResourceSelectorDialog == null) {
409        hiveResourceSelectorDialog = new HiveResourceSelectorDialog(Content.Job.Id, Content.Job.ProjectId);
[16662]410      } else if (hiveResourceSelectorDialog.JobId != Content.Job.Id) {
[16386]411        hiveResourceSelectorDialog.JobId = Content.Job.Id;
412        hiveResourceSelectorDialog.SelectedProjectId = Content.Job.ProjectId;
413        hiveResourceSelectorDialog.SelectedResourceIds = Content.Job.ResourceIds;
414
415        if (originalJobProjectAssignment.ContainsKey(Content.Job.Id)) {
416          hiveResourceSelectorDialog.ProjectId = originalJobProjectAssignment[Content.Job.Id];
417        } else {
418          hiveResourceSelectorDialog.ProjectId = Guid.Empty;
419        }
[16662]420      } else if (hiveResourceSelectorDialog.JobId == Guid.Empty && Content.Job.Id == Guid.Empty) {
[16386]421        hiveResourceSelectorDialog.JobId = Content.Job.Id;
422        hiveResourceSelectorDialog.ProjectId = Guid.Empty;
423        hiveResourceSelectorDialog.SelectedProjectId = Content.Job.ProjectId;
424        hiveResourceSelectorDialog.SelectedResourceIds = Content.Job.ResourceIds;
425      } else {
426        hiveResourceSelectorDialog.SelectedProjectId = Content.Job.ProjectId;
427        hiveResourceSelectorDialog.SelectedResourceIds = Content.Job.ResourceIds;
428      }
429
[7910]430      if (hiveResourceSelectorDialog.ShowDialog(this) == DialogResult.OK) {
[16386]431        selectedProject = hiveResourceSelectorDialog.SelectedProject;
[16662]432        if (selectedProject != null) {
[16386]433          Content.Job.ProjectId = selectedProject.Id;
434          Content.Job.ResourceIds = hiveResourceSelectorDialog.SelectedResources.Select(x => x.Id).ToList();
435
436          var cores = hiveResourceSelectorDialog.SelectedResources
437            .Union(hiveResourceSelectorDialog.SelectedResources
438              .SelectMany(x => HiveClient.Instance.GetAvailableResourceDescendants(x.Id)))
439            .OfType<Slave>()
440            .Distinct()
441            .Sum(x => x.Cores);
442
443          projectNameTextBox.Text = HiveClient.Instance.GetProjectAncestry(selectedProject.Id) + "";
444          projectNameTextBox.Text += "   (" + (cores.HasValue ? cores.Value.ToString() : "0") + " cores)";
445
446        } else {
447          selectedProject = null;
448          projectNameTextBox.Text = string.Empty;
449          Content.Job.ProjectId = Guid.Empty;
450          Content.Job.ResourceIds = null;
[7910]451        }
[16386]452        SetEnabledStateOfExecutableButtons();
[7910]453      }
454    }
455
[6976]456    private void startButton_Click(object sender, EventArgs e) {
[7068]457      if (nameTextBox.Text.Trim() == string.Empty) {
458        MessageBox.Show("Please enter a name for the job before uploading it!", "HeuristicLab Hive Job Manager", MessageBoxButtons.OK, MessageBoxIcon.Information);
[16386]459      } else if (Content.Job.ProjectId == null || Content.Job.ProjectId == Guid.Empty) {
460        MessageBox.Show("Please select a project before uploading the job!", "HeuristicLab Hive Job Manager", MessageBoxButtons.OK, MessageBoxIcon.Information);
461      } else if (Content.Job.ResourceIds == null || !Content.Job.ResourceIds.Any()) {
462        MessageBox.Show("Please select resources before uploading the job!", "HeuristicLab Hive Job Manager", MessageBoxButtons.OK, MessageBoxIcon.Information);
[7162]463      } else if (Content.ExecutionState == ExecutionState.Paused) {
[7156]464        var task = System.Threading.Tasks.Task.Factory.StartNew(ResumeJobAsync, Content);
465        task.ContinueWith((t) => {
[9893]466          Content.Progress.Finish();
[7156]467          MessageBox.Show("An error occured resuming the job. See the log for more information.", "HeuristicLab Hive Job Manager", MessageBoxButtons.OK, MessageBoxIcon.Error);
468          Content.Log.LogException(t.Exception);
469        }, TaskContinuationOptions.OnlyOnFaulted);
[7068]470      } else {
471        HiveClient.StartJob((Exception ex) => ErrorHandling.ShowErrorDialog(this, "Start failed.", ex), Content, new CancellationToken());
[16386]472        UpdateSelectorDialog();
[7068]473      }
[6976]474    }
[7156]475
[6976]476    private void pauseButton_Click(object sender, EventArgs e) {
[7156]477      var task = System.Threading.Tasks.Task.Factory.StartNew(PauseJobAsync, Content);
[7162]478      task.ContinueWith((t) => {
[9893]479        Content.Progress.Finish();
[7156]480        MessageBox.Show("An error occured pausing the job. See the log for more information.", "HeuristicLab Hive Job Manager", MessageBoxButtons.OK, MessageBoxIcon.Error);
481        Content.Log.LogException(t.Exception);
482      }, TaskContinuationOptions.OnlyOnFaulted);
[7162]483    }
[7156]484
[6976]485    private void stopButton_Click(object sender, EventArgs e) {
[7156]486      var task = System.Threading.Tasks.Task.Factory.StartNew(StopJobAsync, Content);
487      task.ContinueWith((t) => {
[9893]488        Content.Progress.Finish();
[7156]489        MessageBox.Show("An error occured stopping the job. See the log for more information.", "HeuristicLab Hive Job Manager", MessageBoxButtons.OK, MessageBoxIcon.Error);
490        Content.Log.LogException(t.Exception);
491      }, TaskContinuationOptions.OnlyOnFaulted);
[6976]492    }
493
[7156]494    private void PauseJobAsync(object job) {
[16662]495      Content.Progress.Start("Pausing job...", ProgressMode.Indeterminate);
[7156]496      HiveClient.PauseJob((RefreshableJob)job);
[9893]497      Content.Progress.Finish();
[7156]498    }
499
500    private void StopJobAsync(object job) {
[16662]501      Content.Progress.Start("Stopping job...", ProgressMode.Indeterminate);
[7156]502      HiveClient.StopJob((RefreshableJob)job);
[9893]503      Content.Progress.Finish();
[7156]504    }
505
506    private void ResumeJobAsync(object job) {
[16662]507      Content.Progress.Start("Resuming job...", ProgressMode.Indeterminate);
[7156]508      HiveClient.ResumeJob((RefreshableJob)job);
[9893]509      Content.Progress.Finish();
[7156]510    }
511
[6976]512    private void nameTextBox_Validated(object sender, EventArgs e) {
[9219]513      if (!SuppressEvents && Content.Job != null && Content.Job.Name != nameTextBox.Text)
[6976]514        Content.Job.Name = nameTextBox.Text;
515    }
516
[16386]517    private void descriptionTextBox_Validated(object sender, EventArgs e) {
518      if (!SuppressEvents && Content.Job != null && Content.Job.Description != descriptionTextBox.Text)
519        Content.Job.Description = descriptionTextBox.Text;
520    }
521
[6976]522    private void resourceNamesTextBox_Validated(object sender, EventArgs e) {
[16386]523      //if (!SuppressEvents && Content.Job != null && Content.Job.ResourceNames != resourceNamesTextBox.Text)
524      //  Content.Job.ResourceNames = resourceNamesTextBox.Text;
[6976]525    }
526
[8090]527    private void refreshAutomaticallyCheckBox_CheckedChanged(object sender, EventArgs e) {
[8914]528      if (Content != null && !SuppressEvents) Content.RefreshAutomatically = refreshAutomaticallyCheckBox.Checked;
[6976]529    }
530
531    private void refreshButton_Click(object sender, EventArgs e) {
532      var invoker = new Action<RefreshableJob>(HiveClient.LoadJob);
533      invoker.BeginInvoke(Content, (ar) => {
534        try {
535          invoker.EndInvoke(ar);
[16386]536        } catch (Exception ex) {
537          ThreadPool.QueueUserWorkItem(delegate (object exception) { ErrorHandling.ShowErrorDialog(this, (Exception)exception); }, ex);
[6976]538        }
[16386]539      }, null);
540      UpdateSelectorDialog();
541    }
542
543    private void updateButton_Click(object sender, EventArgs e) {
544      if (Content.ExecutionState == ExecutionState.Stopped) {
545        MessageBox.Show("Job cannot be updated once it stopped.", "HeuristicLab Hive Job Manager", MessageBoxButtons.OK, MessageBoxIcon.Information);
546        return;
547      }
548
549      var invoker = new Action<RefreshableJob>(HiveClient.UpdateJob);
550      invoker.BeginInvoke(Content, (ar) => {
551        try {
552          invoker.EndInvoke(ar);
553        } catch (Exception ex) {
554          ThreadPool.QueueUserWorkItem(delegate (object exception) { ErrorHandling.ShowErrorDialog(this, (Exception)exception); }, ex);
[6976]555        }
556      }, null);
[16386]557      UpdateSelectorDialog();
[6976]558    }
559
[16386]560    private void UnloadButton_Click(object sender, EventArgs e) {
561      Content.Unload();
562      runCollectionViewHost.Content = null;
563      stateLogViewHost.Content = null;
564      hiveExperimentPermissionListView.Content = null;
565      jobsTreeView.Content = null;
566
567      SetEnabledStateOfControls();
568    }
569
[6976]570    private void refreshPermissionsButton_Click(object sender, EventArgs e) {
[7029]571      if (this.Content.Job.Id == Guid.Empty) {
572        MessageBox.Show("You have to upload the Job first before you can share it.", "HeuristicLab Hive Job Manager", MessageBoxButtons.OK, MessageBoxIcon.Information);
573      } else {
574        hiveExperimentPermissionListView.Content = HiveClient.GetJobPermissions(this.Content.Job.Id);
575      }
[6976]576    }
577    #endregion
578
579    #region Helpers
580    private void SetEnabledStateOfExecutableButtons() {
581      if (Content == null) {
[14901]582        startButton.Enabled = pauseButton.Enabled = stopButton.Enabled = false;
[6976]583      } else {
[16662]584        startButton.Enabled = Content.IsControllable && Content.HiveTasks != null && Content.HiveTasks.Count > 0
585          && Content.Job.ProjectId != Guid.Empty && Content.Job.ResourceIds != null && Content.Job.ResourceIds.Any()
[16386]586          && (Content.ExecutionState == ExecutionState.Prepared || Content.ExecutionState == ExecutionState.Paused) && !Content.IsProgressing;
[8159]587        pauseButton.Enabled = Content.IsControllable && Content.ExecutionState == ExecutionState.Started && !Content.IsProgressing;
[14901]588        stopButton.Enabled = Content.IsControllable && (Content.ExecutionState == ExecutionState.Started || Content.ExecutionState == ExecutionState.Paused) && !Content.IsProgressing;
[6976]589      }
590    }
[16662]591
[16386]592    private Project GetProject(Guid projectId) {
593      return HiveServiceLocator.Instance.CallHiveService(s => s.GetProject(projectId));
594    }
595
596    private void UpdateSelectorDialog() {
[16662]597      if (hiveResourceSelectorDialog != null) {
[16386]598        hiveResourceSelectorDialog = null;
599        //hiveResourceSelectorDialog.JobId = Content.Job.Id;
600        //hiveResourceSelectorDialog.SelectedProjectId = Content.Job.ProjectId;
601        //hiveResourceSelectorDialog.SelectedResourceIds = Content.Job.ResourceIds;
602      }
603    }
[6976]604    #endregion
605
606    #region Drag & Drop
607    private void jobsTreeView_DragOver(object sender, DragEventArgs e) {
608      jobsTreeView_DragEnter(sender, e);
609    }
610
611    private void jobsTreeView_DragEnter(object sender, DragEventArgs e) {
612      e.Effect = DragDropEffects.None;
[11079]613      var obj = (IDeepCloneable)e.Data.GetData(Constants.DragDropDataFormat);
614
[10130]615      Type objType = obj.GetType();
[11079]616      if (ItemTask.IsTypeSupported(objType)) {
[7067]617        if (Content.Id != Guid.Empty) e.Effect = DragDropEffects.None;
618        else if ((e.KeyState & 32) == 32) e.Effect = DragDropEffects.Link;  // ALT key
[6976]619        else if (e.AllowedEffect.HasFlag(DragDropEffects.Copy)) e.Effect = DragDropEffects.Copy;
620      }
621    }
622
623    private void jobsTreeView_DragDrop(object sender, DragEventArgs e) {
624      if (e.Effect != DragDropEffects.None) {
[11079]625        var obj = (IItem)e.Data.GetData(Constants.DragDropDataFormat);
[6976]626
[10150]627        IItem newObj = null;
[10130]628        if (e.Effect.HasFlag(DragDropEffects.Copy)) {
[11079]629          newObj = (IItem)obj.Clone();
[10130]630        } else {
631          newObj = obj;
632        }
633
634        //IOptimizer and IExecutables need some special care
635        if (newObj is IOptimizer) {
636          ((IOptimizer)newObj).Runs.Clear();
637        }
638        if (newObj is IExecutable) {
[11079]639          IExecutable exec = (IExecutable)newObj;
[10130]640          if (exec.ExecutionState != ExecutionState.Prepared) {
641            exec.Prepare();
[7067]642          }
[10130]643        }
[7067]644
[10150]645        ItemTask hiveTask = ItemTask.GetItemTaskForItem(newObj);
[10130]646        Content.HiveTasks.Add(hiveTask.CreateHiveTask());
[6976]647      }
648    }
649    #endregion
650
651    private void tabControl_SelectedIndexChanged(object sender, EventArgs e) {
652      if (tabControl.SelectedTab == permissionTabPage) {
653        if (!Content.IsSharable) {
[7162]654          MessageBox.Show("Unable to load permissions. You have insufficient access privileges.", "HeuristicLab Hive Job Manager", MessageBoxButtons.OK, MessageBoxIcon.Information);
[6976]655          tabControl.SelectedTab = tasksTabPage;
656        }
657      }
658    }
659
660    private RunCollection GetAllRunsFromJob(RefreshableJob job) {
661      if (job != null) {
[8962]662        RunCollection runs = new RunCollection() { OptimizerName = job.ItemName };
[6976]663
[8700]664        foreach (HiveTask subTask in job.HiveTasks) {
665          if (subTask is OptimizerHiveTask) {
666            OptimizerHiveTask ohTask = subTask as OptimizerHiveTask;
[16386]667            ohTask.ExecuteReadActionOnItemTask(new Action(delegate () {
[8939]668              runs.AddRange(ohTask.ItemTask.Item.Runs);
669            }));
[8700]670          }
[6976]671        }
672        return runs;
673      } else {
674        return null;
675      }
676    }
[9219]677
[6976]678  }
[10130]679}
Note: See TracBrowser for help on using the repository browser.