Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Clients.Hive.JobManager/3.3/Views/RefreshableHiveJobView.cs @ 18190

Last change on this file since 18190 was 17180, checked in by swagner, 5 years ago

#2875: Removed years in copyrights

File size: 30.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 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.ComponentModel;
24using System.Linq;
25using System.Threading;
26using System.Threading.Tasks;
27using System.Windows.Forms;
28using HeuristicLab.Collections;
29using HeuristicLab.Common;
30using HeuristicLab.Core;
31using HeuristicLab.MainForm;
32using HeuristicLab.MainForm.WindowsForms;
33using HeuristicLab.Optimization;
34using HeuristicLab.PluginInfrastructure;
35using System.Collections.Generic;
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 {
44    private HiveResourceSelectorDialog hiveResourceSelectorDialog;
45    private bool SuppressEvents { get; set; }
46    private object runCollectionViewLocker = new object();
47    private Project selectedProject;
48    private Dictionary<Guid, Guid> originalJobProjectAssignment = new Dictionary<Guid, Guid>();
49
50    public new RefreshableJob Content {
51      get { return (RefreshableJob)base.Content; }
52      set {
53        base.Content = value;
54      }
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);
76      Content.TaskReceived += new EventHandler(Content_TaskReceived);
77      Progress.Show(this, Content.Progress);
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);
91      Content.TaskReceived -= new EventHandler(Content_TaskReceived);
92      Progress.Hide(this, false);
93      DeregisterHiveExperimentEvents();
94      DeregisterHiveTasksEvents();
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
106    private void RegisterHiveTasksEvents() {
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    }
111    private void DeregisterHiveTasksEvents() {
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();
119      SuppressEvents = true;
120      try {
121        if (Content == null) {
122          nameTextBox.Text = string.Empty;
123          descriptionTextBox.Text = string.Empty;
124          executionTimeTextBox.Text = string.Empty;
125          projectNameTextBox.Text = string.Empty;
126          refreshAutomaticallyCheckBox.Checked = false;
127          lock (runCollectionViewLocker) {
128            runCollectionViewHost.Content = null;
129          }
130          logView.Content = null;
131          jobsTreeView.Content = null;
132          hiveExperimentPermissionListView.Content = null;
133          stateLogViewHost.Content = null;
134        } else {
135          if (Content.Job != null
136            && Content.Job.Id != Guid.Empty
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)";
161              }
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
169            if (hiveResourceSelectorDialog == null)
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
201          nameTextBox.Text = Content.Job.Name;
202          descriptionTextBox.Text = Content.Job.Description;
203          executionTimeTextBox.Text = Content.ExecutionTime.ToString();
204          refreshAutomaticallyCheckBox.Checked = Content.RefreshAutomatically;
205
206          logView.Content = Content.Log;
207          lock (runCollectionViewLocker) {
208            runCollectionViewHost.Content = GetAllRunsFromJob(Content);
209          }
210        }
211      } finally {
212        SuppressEvents = false;
213      }
214      hiveExperimentPermissionListView.Content = null; // has to be filled by refresh
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
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;
231      descriptionTextBox.Enabled = !Locked;
232      projectNameTextBox.Enabled = !Locked;
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
243    protected override void SetEnabledStateOfControls() {
244      base.SetEnabledStateOfControls();
245      if (!Locked) {
246        executionTimeTextBox.Enabled = Content != null;
247        jobsTextBox.ReadOnly = true;
248        calculatingTextBox.ReadOnly = true;
249        finishedTextBox.ReadOnly = true;
250
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;
255
256          this.nameTextBox.ReadOnly = Content.IsProgressing;
257          this.descriptionTextBox.ReadOnly = Content.IsProgressing;
258          this.searchButton.Enabled = !Content.IsProgressing && Content.ExecutionState != ExecutionState.Stopped;
259          this.jobsTreeView.ReadOnly = !Content.IsControllable || Content.ExecutionState != ExecutionState.Prepared || alreadyUploaded || Content.IsProgressing;
260
261          this.refreshAutomaticallyCheckBox.Enabled = Content.IsControllable && alreadyUploaded && jobsLoaded && (Content.ExecutionState == ExecutionState.Started || Content.ExecutionState == ExecutionState.Paused) && !Content.IsProgressing;
262          this.refreshButton.Enabled = Content.IsDownloadable && alreadyUploaded && !Content.IsProgressing;
263          this.updateButton.Enabled = Content.ExecutionState != ExecutionState.Prepared && Content.ExecutionState != ExecutionState.Stopped && !Content.IsProgressing;
264
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
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
281    void Content_TaskReceived(object sender, EventArgs e) {
282      lock (runCollectionViewLocker) {
283        runCollectionViewHost.Content = GetAllRunsFromJob(Content);
284      }
285    }
286
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    }
317
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;
338          RegisterHiveTasksEvents();
339        } else {
340          jobsTreeView.Content = null;
341        }
342        SetEnabledStateOfControls();
343      }
344    }
345
346    void Content_Loaded(object sender, EventArgs e) {
347      lock (runCollectionViewLocker) {
348        runCollectionViewHost.Content = GetAllRunsFromJob(Content);
349      }
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) {
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      }
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
407    private void searchButton_Click(object sender, EventArgs e) {
408      if (hiveResourceSelectorDialog == null) {
409        hiveResourceSelectorDialog = new HiveResourceSelectorDialog(Content.Job.Id, Content.Job.ProjectId);
410      } else if (hiveResourceSelectorDialog.JobId != Content.Job.Id) {
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        }
420      } else if (hiveResourceSelectorDialog.JobId == Guid.Empty && Content.Job.Id == Guid.Empty) {
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
430      if (hiveResourceSelectorDialog.ShowDialog(this) == DialogResult.OK) {
431        selectedProject = hiveResourceSelectorDialog.SelectedProject;
432        if (selectedProject != null) {
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;
451        }
452        SetEnabledStateOfExecutableButtons();
453      }
454    }
455
456    private void startButton_Click(object sender, EventArgs e) {
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);
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);
463      } else if (Content.ExecutionState == ExecutionState.Paused) {
464        var task = System.Threading.Tasks.Task.Factory.StartNew(ResumeJobAsync, Content);
465        task.ContinueWith((t) => {
466          Content.Progress.Finish();
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);
470      } else {
471        HiveClient.StartJob((Exception ex) => ErrorHandling.ShowErrorDialog(this, "Start failed.", ex), Content, new CancellationToken());
472        UpdateSelectorDialog();
473      }
474    }
475
476    private void pauseButton_Click(object sender, EventArgs e) {
477      var task = System.Threading.Tasks.Task.Factory.StartNew(PauseJobAsync, Content);
478      task.ContinueWith((t) => {
479        Content.Progress.Finish();
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);
483    }
484
485    private void stopButton_Click(object sender, EventArgs e) {
486      var task = System.Threading.Tasks.Task.Factory.StartNew(StopJobAsync, Content);
487      task.ContinueWith((t) => {
488        Content.Progress.Finish();
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);
492    }
493
494    private void PauseJobAsync(object job) {
495      Content.Progress.Start("Pausing job...", ProgressMode.Indeterminate);
496      HiveClient.PauseJob((RefreshableJob)job);
497      Content.Progress.Finish();
498    }
499
500    private void StopJobAsync(object job) {
501      Content.Progress.Start("Stopping job...", ProgressMode.Indeterminate);
502      HiveClient.StopJob((RefreshableJob)job);
503      Content.Progress.Finish();
504    }
505
506    private void ResumeJobAsync(object job) {
507      Content.Progress.Start("Resuming job...", ProgressMode.Indeterminate);
508      HiveClient.ResumeJob((RefreshableJob)job);
509      Content.Progress.Finish();
510    }
511
512    private void nameTextBox_Validated(object sender, EventArgs e) {
513      if (!SuppressEvents && Content.Job != null && Content.Job.Name != nameTextBox.Text)
514        Content.Job.Name = nameTextBox.Text;
515    }
516
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
522    private void resourceNamesTextBox_Validated(object sender, EventArgs e) {
523      //if (!SuppressEvents && Content.Job != null && Content.Job.ResourceNames != resourceNamesTextBox.Text)
524      //  Content.Job.ResourceNames = resourceNamesTextBox.Text;
525    }
526
527    private void refreshAutomaticallyCheckBox_CheckedChanged(object sender, EventArgs e) {
528      if (Content != null && !SuppressEvents) Content.RefreshAutomatically = refreshAutomaticallyCheckBox.Checked;
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);
536        } catch (Exception ex) {
537          ThreadPool.QueueUserWorkItem(delegate (object exception) { ErrorHandling.ShowErrorDialog(this, (Exception)exception); }, ex);
538        }
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);
555        }
556      }, null);
557      UpdateSelectorDialog();
558    }
559
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
570    private void refreshPermissionsButton_Click(object sender, EventArgs e) {
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      }
576    }
577    #endregion
578
579    #region Helpers
580    private void SetEnabledStateOfExecutableButtons() {
581      if (Content == null) {
582        startButton.Enabled = pauseButton.Enabled = stopButton.Enabled = false;
583      } else {
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()
586          && (Content.ExecutionState == ExecutionState.Prepared || Content.ExecutionState == ExecutionState.Paused) && !Content.IsProgressing;
587        pauseButton.Enabled = Content.IsControllable && Content.ExecutionState == ExecutionState.Started && !Content.IsProgressing;
588        stopButton.Enabled = Content.IsControllable && (Content.ExecutionState == ExecutionState.Started || Content.ExecutionState == ExecutionState.Paused) && !Content.IsProgressing;
589      }
590    }
591
592    private Project GetProject(Guid projectId) {
593      return HiveServiceLocator.Instance.CallHiveService(s => s.GetProject(projectId));
594    }
595
596    private void UpdateSelectorDialog() {
597      if (hiveResourceSelectorDialog != null) {
598        hiveResourceSelectorDialog = null;
599        //hiveResourceSelectorDialog.JobId = Content.Job.Id;
600        //hiveResourceSelectorDialog.SelectedProjectId = Content.Job.ProjectId;
601        //hiveResourceSelectorDialog.SelectedResourceIds = Content.Job.ResourceIds;
602      }
603    }
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;
613      var obj = (IDeepCloneable)e.Data.GetData(Constants.DragDropDataFormat);
614
615      Type objType = obj.GetType();
616      if (ItemTask.IsTypeSupported(objType)) {
617        if (Content.Id != Guid.Empty) e.Effect = DragDropEffects.None;
618        else if ((e.KeyState & 32) == 32) e.Effect = DragDropEffects.Link;  // ALT key
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) {
625        var obj = (IItem)e.Data.GetData(Constants.DragDropDataFormat);
626
627        IItem newObj = null;
628        if (e.Effect.HasFlag(DragDropEffects.Copy)) {
629          newObj = (IItem)obj.Clone();
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) {
639          IExecutable exec = (IExecutable)newObj;
640          if (exec.ExecutionState != ExecutionState.Prepared) {
641            exec.Prepare();
642          }
643        }
644
645        ItemTask hiveTask = ItemTask.GetItemTaskForItem(newObj);
646        Content.HiveTasks.Add(hiveTask.CreateHiveTask());
647      }
648    }
649    #endregion
650
651    private void tabControl_SelectedIndexChanged(object sender, EventArgs e) {
652      if (tabControl.SelectedTab == permissionTabPage) {
653        if (!Content.IsSharable) {
654          MessageBox.Show("Unable to load permissions. You have insufficient access privileges.", "HeuristicLab Hive Job Manager", MessageBoxButtons.OK, MessageBoxIcon.Information);
655          tabControl.SelectedTab = tasksTabPage;
656        }
657      }
658    }
659
660    private RunCollection GetAllRunsFromJob(RefreshableJob job) {
661      if (job != null) {
662        RunCollection runs = new RunCollection() { OptimizerName = job.ItemName };
663
664        foreach (HiveTask subTask in job.HiveTasks) {
665          if (subTask is OptimizerHiveTask) {
666            OptimizerHiveTask ohTask = subTask as OptimizerHiveTask;
667            ohTask.ExecuteReadActionOnItemTask(new Action(delegate () {
668              runs.AddRange(ohTask.ItemTask.Item.Runs);
669            }));
670          }
671        }
672        return runs;
673      } else {
674        return null;
675      }
676    }
677
678  }
679}
Note: See TracBrowser for help on using the repository browser.