Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 16117 was 16117, checked in by jkarder, 6 years ago

#2839: merged [15377-16116/branches/2839_HiveProjectManagement] into trunk

File size: 28.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 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      MainFormManager.GetMainForm<HeuristicLab.MainForm.WindowsForms.MainForm>().AddOperationProgressToView(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      MainFormManager.GetMainForm<HeuristicLab.MainForm.WindowsForms.MainForm>().RemoveOperationProgressFromView(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          if (Content.Job != null && Content.Job.ProjectId == Guid.Empty) {
142            if (HiveClient.Instance != null && HiveClient.Instance.Projects != null && HiveClient.Instance.Projects.Count == 1) {
143              var p = HiveClient.Instance.Projects.FirstOrDefault();
144              if (p != null && p.Id != Guid.Empty) {
145                hiveResourceSelectorDialog = new HiveResourceSelectorDialog(Content.Job.Id, Content.Job.ProjectId);
146                Content.Job.ProjectId = p.Id;
147                Content.Job.ResourceIds = HiveClient.Instance.GetAvailableResourcesForProject(p.Id).Select(x => x.Id).ToList();
148                hiveResourceSelectorDialog.SelectedProjectId = Content.Job.ProjectId;
149                hiveResourceSelectorDialog.SelectedResourceIds = Content.Job.ResourceIds;
150              }               
151            }
152          }
153
154
155          nameTextBox.Text = Content.Job.Name;
156          descriptionTextBox.Text = Content.Job.Description;
157          executionTimeTextBox.Text = Content.ExecutionTime.ToString();
158          refreshAutomaticallyCheckBox.Checked = Content.RefreshAutomatically;
159
160          // project look up
161          if(Content.Job.ProjectId != null && Content.Job.ProjectId != Guid.Empty) {
162            if(selectedProject == null || selectedProject.Id != Content.Job.ProjectId) {
163              selectedProject = GetProject(Content.Job.ProjectId);
164              if (selectedProject != null) {
165                projectNameTextBox.Text = selectedProject.Name;
166              } else {
167                projectNameTextBox.Text = string.Empty;
168              }
169            }
170          } else {
171            selectedProject = null;
172            projectNameTextBox.Text = string.Empty;
173            Content.Job.ResourceIds = null;
174          }
175         
176          logView.Content = Content.Log;
177          lock (runCollectionViewLocker) {
178            runCollectionViewHost.Content = GetAllRunsFromJob(Content);
179          }
180        }
181      } finally {
182        SuppressEvents = false;
183      }
184      hiveExperimentPermissionListView.Content = null; // has to be filled by refresh button
185      Content_JobStatisticsChanged(this, EventArgs.Empty);
186      Content_HiveExperimentChanged(this, EventArgs.Empty);
187      Content_HiveTasksChanged(this, EventArgs.Empty);
188      Content_StateLogListChanged(this, EventArgs.Empty);
189      HiveExperiment_PropertyChanged(this, new PropertyChangedEventArgs("Id"));
190      SetEnabledStateOfControls();
191    }
192
193    protected override void OnLockedChanged() {
194      base.OnLockedChanged();
195      executionTimeTextBox.Enabled = !Locked;
196      jobsTextBox.Enabled = !Locked;
197      calculatingTextBox.Enabled = !Locked;
198      finishedTextBox.Enabled = !Locked;
199      tabControl.Enabled = !Locked;
200      nameTextBox.Enabled = !Locked;
201      descriptionTextBox.Enabled = !Locked;
202      projectNameTextBox.Enabled = !Locked;
203      searchButton.Enabled = !Locked;
204      jobsTreeView.Enabled = !Locked;
205      refreshAutomaticallyCheckBox.Enabled = !Locked;
206      refreshButton.Enabled = !Locked;
207      UnloadButton.Enabled = !Locked;
208      startButton.Enabled = !Locked;
209      pauseButton.Enabled = !Locked;
210      stopButton.Enabled = !Locked;
211    }
212
213    protected override void SetEnabledStateOfControls() {
214      base.SetEnabledStateOfControls();
215      if (!Locked) {
216        executionTimeTextBox.Enabled = Content != null;
217        jobsTextBox.ReadOnly = true;
218        calculatingTextBox.ReadOnly = true;
219        finishedTextBox.ReadOnly = true;
220
221        if (Content != null) {
222          bool alreadyUploaded = Content.Id != Guid.Empty;
223          bool jobsLoaded = Content.HiveTasks != null && Content.HiveTasks.All(x => x.Task.Id != Guid.Empty);
224          tabControl.Enabled = !Content.IsProgressing;
225
226          this.nameTextBox.ReadOnly = Content.IsProgressing;
227          this.descriptionTextBox.ReadOnly = Content.IsProgressing;
228          this.searchButton.Enabled = !Content.IsProgressing && Content.ExecutionState != ExecutionState.Stopped;
229          this.jobsTreeView.ReadOnly = !Content.IsControllable || Content.ExecutionState != ExecutionState.Prepared || alreadyUploaded || Content.IsProgressing;
230
231          this.refreshAutomaticallyCheckBox.Enabled = Content.IsControllable && alreadyUploaded && jobsLoaded && (Content.ExecutionState == ExecutionState.Started || Content.ExecutionState == ExecutionState.Paused) && !Content.IsProgressing;
232          this.refreshButton.Enabled = Content.IsDownloadable && alreadyUploaded && !Content.IsProgressing;
233          this.updateButton.Enabled = Content.ExecutionState != ExecutionState.Prepared && Content.ExecutionState != ExecutionState.Stopped && !Content.IsProgressing;
234
235          this.UnloadButton.Enabled = Content.HiveTasks != null && Content.HiveTasks.Count > 0 && alreadyUploaded && !Content.IsProgressing;
236        }
237        SetEnabledStateOfExecutableButtons();
238        tabControl_SelectedIndexChanged(this, EventArgs.Empty); // ensure sharing tabpage is disabled
239      }
240    }
241
242    protected override void OnClosed(FormClosedEventArgs e) {
243      if (Content != null) {
244        if (Content.RefreshAutomatically)
245          Content.StopResultPolling();
246      }
247      base.OnClosed(e);
248    }
249
250    #region Content Events
251    void Content_TaskReceived(object sender, EventArgs e) {
252      lock (runCollectionViewLocker) {
253        runCollectionViewHost.Content = GetAllRunsFromJob(Content);
254      }
255    }
256
257    private void HiveTasks_ItemsAdded(object sender, CollectionItemsChangedEventArgs<HiveTask> e) {
258      if (InvokeRequired)
259        Invoke(new CollectionItemsChangedEventHandler<HiveTask>(HiveTasks_ItemsAdded), sender, e);
260      else {
261        SetEnabledStateOfControls();
262      }
263    }
264
265    private void HiveTasks_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<HiveTask> e) {
266      if (InvokeRequired)
267        Invoke(new CollectionItemsChangedEventHandler<HiveTask>(HiveTasks_ItemsRemoved), sender, e);
268      else {
269        SetEnabledStateOfControls();
270      }
271    }
272
273    private void HiveTasks_CollectionReset(object sender, CollectionItemsChangedEventArgs<HiveTask> e) {
274      if (InvokeRequired)
275        Invoke(new CollectionItemsChangedEventHandler<HiveTask>(HiveTasks_CollectionReset), sender, e);
276      else {
277        SetEnabledStateOfControls();
278      }
279    }
280
281    private void Content_ExecutionStateChanged(object sender, EventArgs e) {
282      if (InvokeRequired)
283        Invoke(new EventHandler(Content_ExecutionStateChanged), sender, e);
284      else
285        SetEnabledStateOfControls();
286    }
287
288    private void Content_ExecutionTimeChanged(object sender, EventArgs e) {
289      if (InvokeRequired)
290        Invoke(new EventHandler(Content_ExecutionTimeChanged), sender, e);
291      else
292        executionTimeTextBox.Text = Content.ExecutionTime.ToString();
293    }
294    private void Content_RefreshAutomaticallyChanged(object sender, EventArgs e) {
295      if (InvokeRequired)
296        Invoke(new EventHandler(Content_RefreshAutomaticallyChanged), sender, e);
297      else {
298        refreshAutomaticallyCheckBox.Checked = Content.RefreshAutomatically;
299        SetEnabledStateOfControls();
300      }
301    }
302    private void Content_HiveTasksChanged(object sender, EventArgs e) {
303      if (InvokeRequired)
304        Invoke(new EventHandler(Content_HiveTasksChanged), sender, e);
305      else {
306        if (Content != null && Content.HiveTasks != null) {
307          jobsTreeView.Content = Content.HiveTasks;
308          RegisterHiveTasksEvents();
309        } else {
310          jobsTreeView.Content = null;
311        }
312        SetEnabledStateOfControls();
313      }
314    }
315
316    void Content_Loaded(object sender, EventArgs e) {
317      lock (runCollectionViewLocker) {
318        runCollectionViewHost.Content = GetAllRunsFromJob(Content);
319      }
320    }
321
322    private void Content_HiveExperimentChanged(object sender, EventArgs e) {
323      if (Content != null && Content.Job != null) {
324        RegisterHiveExperimentEvents();
325      }
326    }
327    private void Content_IsControllableChanged(object sender, EventArgs e) {
328      SetEnabledStateOfControls();
329    }
330    private void Content_JobStatisticsChanged(object sender, EventArgs e) {
331      if (InvokeRequired)
332        Invoke(new EventHandler(Content_JobStatisticsChanged), sender, e);
333      else {
334        if (Content != null) {
335          jobsTextBox.Text = (Content.Job.JobCount - Content.Job.CalculatingCount - Content.Job.FinishedCount).ToString();
336          calculatingTextBox.Text = Content.Job.CalculatingCount.ToString();
337          finishedTextBox.Text = Content.Job.FinishedCount.ToString();
338        } else {
339          jobsTextBox.Text = "0";
340          calculatingTextBox.Text = "0";
341          finishedTextBox.Text = "0";
342        }
343      }
344    }
345    private void Content_ExceptionOccured(object sender, EventArgs<Exception> e) {
346      if (InvokeRequired)
347        Invoke(new EventHandler<EventArgs<Exception>>(Content_ExceptionOccured), sender, e);
348      else {
349        //don't show the error dialog when downloading tasks, the HiveClient will throw an exception and the dialog will be shown then
350        if (sender.GetType() != typeof(ConcurrentTaskDownloader<ItemTask>) && sender.GetType() != typeof(TaskDownloader)) {
351          ErrorHandling.ShowErrorDialog(this, e.Value);
352        }
353      }
354    }
355    private void Content_StateLogListChanged(object sender, EventArgs e) {
356      if (InvokeRequired)
357        Invoke(new EventHandler(Content_StateLogListChanged), sender, e);
358      else {
359        UpdateStateLogList();
360      }
361    }
362
363    private void UpdateStateLogList() {
364      if (Content != null && this.Content.Job != null) {
365        stateLogViewHost.Content = this.Content.StateLogList;
366      } else {
367        stateLogViewHost.Content = null;
368      }
369    }
370
371    private void HiveExperiment_PropertyChanged(object sender, PropertyChangedEventArgs e) {
372      if (this.Content != null && e.PropertyName == "Id") this.hiveExperimentPermissionListView.HiveExperimentId = this.Content.Job.Id;
373    }
374    #endregion
375
376    #region Control events
377    private void searchButton_Click(object sender, EventArgs e) {
378      if (hiveResourceSelectorDialog == null) {
379        hiveResourceSelectorDialog = new HiveResourceSelectorDialog(Content.Job.Id, Content.Job.ProjectId);
380      } else if(hiveResourceSelectorDialog.JobId != Content.Job.Id) {
381        hiveResourceSelectorDialog.JobId = Content.Job.Id;
382        hiveResourceSelectorDialog.SelectedProjectId = Content.Job.ProjectId;
383        hiveResourceSelectorDialog.SelectedResourceIds = Content.Job.ResourceIds;
384
385        if (originalJobProjectAssignment.ContainsKey(Content.Job.Id)) {
386          hiveResourceSelectorDialog.ProjectId = originalJobProjectAssignment[Content.Job.Id];
387        } else {
388          hiveResourceSelectorDialog.ProjectId = Guid.Empty;
389        }
390      } else if(hiveResourceSelectorDialog.JobId == Guid.Empty && Content.Job.Id == Guid.Empty) {
391        hiveResourceSelectorDialog.JobId = Content.Job.Id;
392        hiveResourceSelectorDialog.ProjectId = Guid.Empty;
393        hiveResourceSelectorDialog.SelectedProjectId = Content.Job.ProjectId;
394        hiveResourceSelectorDialog.SelectedResourceIds = Content.Job.ResourceIds;
395      } else {
396        hiveResourceSelectorDialog.SelectedProjectId = Content.Job.ProjectId;
397        hiveResourceSelectorDialog.SelectedResourceIds = Content.Job.ResourceIds;
398      }
399
400      if (hiveResourceSelectorDialog.ShowDialog(this) == DialogResult.OK) {
401        selectedProject = hiveResourceSelectorDialog.SelectedProject;
402        if(selectedProject != null) {
403          projectNameTextBox.Text = selectedProject.Name;
404          Content.Job.ProjectId = selectedProject.Id;
405          Content.Job.ResourceIds = hiveResourceSelectorDialog.SelectedResources.Select(x => x.Id).ToList();
406        } else {
407          selectedProject = null;
408          projectNameTextBox.Text = string.Empty;
409          Content.Job.ProjectId = Guid.Empty;
410          Content.Job.ResourceIds = null;
411        }
412        SetEnabledStateOfExecutableButtons();
413      }
414    }
415
416    private void startButton_Click(object sender, EventArgs e) {
417      if (nameTextBox.Text.Trim() == string.Empty) {
418        MessageBox.Show("Please enter a name for the job before uploading it!", "HeuristicLab Hive Job Manager", MessageBoxButtons.OK, MessageBoxIcon.Information);
419      } else if (Content.Job.ProjectId == null || Content.Job.ProjectId == Guid.Empty) {
420        MessageBox.Show("Please select a project before uploading the job!", "HeuristicLab Hive Job Manager", MessageBoxButtons.OK, MessageBoxIcon.Information);
421      } else if (Content.Job.ResourceIds == null || !Content.Job.ResourceIds.Any()) {
422        MessageBox.Show("Please select resources before uploading the job!", "HeuristicLab Hive Job Manager", MessageBoxButtons.OK, MessageBoxIcon.Information);
423      } else if (Content.ExecutionState == ExecutionState.Paused) {
424        var task = System.Threading.Tasks.Task.Factory.StartNew(ResumeJobAsync, Content);
425        task.ContinueWith((t) => {
426          Content.Progress.Finish();
427          MessageBox.Show("An error occured resuming the job. See the log for more information.", "HeuristicLab Hive Job Manager", MessageBoxButtons.OK, MessageBoxIcon.Error);
428          Content.Log.LogException(t.Exception);
429        }, TaskContinuationOptions.OnlyOnFaulted);
430      } else {
431        HiveClient.StartJob((Exception ex) => ErrorHandling.ShowErrorDialog(this, "Start failed.", ex), Content, new CancellationToken());
432        UpdateSelectorDialog();
433      }
434    }
435
436    private void pauseButton_Click(object sender, EventArgs e) {
437      var task = System.Threading.Tasks.Task.Factory.StartNew(PauseJobAsync, Content);
438      task.ContinueWith((t) => {
439        Content.Progress.Finish();
440        MessageBox.Show("An error occured pausing the job. See the log for more information.", "HeuristicLab Hive Job Manager", MessageBoxButtons.OK, MessageBoxIcon.Error);
441        Content.Log.LogException(t.Exception);
442      }, TaskContinuationOptions.OnlyOnFaulted);
443    }
444
445    private void stopButton_Click(object sender, EventArgs e) {
446      var task = System.Threading.Tasks.Task.Factory.StartNew(StopJobAsync, Content);
447      task.ContinueWith((t) => {
448        Content.Progress.Finish();
449        MessageBox.Show("An error occured stopping the job. See the log for more information.", "HeuristicLab Hive Job Manager", MessageBoxButtons.OK, MessageBoxIcon.Error);
450        Content.Log.LogException(t.Exception);
451      }, TaskContinuationOptions.OnlyOnFaulted);
452    }
453
454    private void PauseJobAsync(object job) {
455      Content.Progress.Start("Pausing job...");
456      HiveClient.PauseJob((RefreshableJob)job);
457      Content.Progress.Finish();
458    }
459
460    private void StopJobAsync(object job) {
461      Content.Progress.Start("Stopping job...");
462      HiveClient.StopJob((RefreshableJob)job);
463      Content.Progress.Finish();
464    }
465
466    private void ResumeJobAsync(object job) {
467      Content.Progress.Start("Resuming job...");
468      HiveClient.ResumeJob((RefreshableJob)job);
469      Content.Progress.Finish();
470    }
471
472    private void nameTextBox_Validated(object sender, EventArgs e) {
473      if (!SuppressEvents && Content.Job != null && Content.Job.Name != nameTextBox.Text)
474        Content.Job.Name = nameTextBox.Text;
475    }
476
477    private void descriptionTextBox_Validated(object sender, EventArgs e) {
478      if (!SuppressEvents && Content.Job != null && Content.Job.Description != descriptionTextBox.Text)
479        Content.Job.Description = descriptionTextBox.Text;
480    }
481
482    private void resourceNamesTextBox_Validated(object sender, EventArgs e) {
483      //if (!SuppressEvents && Content.Job != null && Content.Job.ResourceNames != resourceNamesTextBox.Text)
484      //  Content.Job.ResourceNames = resourceNamesTextBox.Text;
485    }
486
487    private void refreshAutomaticallyCheckBox_CheckedChanged(object sender, EventArgs e) {
488      if (Content != null && !SuppressEvents) Content.RefreshAutomatically = refreshAutomaticallyCheckBox.Checked;
489    }
490
491    private void refreshButton_Click(object sender, EventArgs e) {
492      var invoker = new Action<RefreshableJob>(HiveClient.LoadJob);
493      invoker.BeginInvoke(Content, (ar) => {
494        try {
495          invoker.EndInvoke(ar);
496        } catch (Exception ex) {
497          ThreadPool.QueueUserWorkItem(delegate (object exception) { ErrorHandling.ShowErrorDialog(this, (Exception)exception); }, ex);
498        }
499      }, null);
500      UpdateSelectorDialog();
501    }
502
503    private void updateButton_Click2(object sender, EventArgs e) {
504      if (Content.ExecutionState == ExecutionState.Stopped) {
505        MessageBox.Show("Job cannot be updated once it stopped.", "HeuristicLab Hive Job Manager", MessageBoxButtons.OK, MessageBoxIcon.Information);
506        return;
507      }
508
509      HiveClient.UpdateJob(
510        (Exception ex) => ErrorHandling.ShowErrorDialog(this, "Update failed.", ex),
511        Content,
512        new CancellationToken());
513      UpdateSelectorDialog();
514    }
515
516    private void updateButton_Click(object sender, EventArgs e) {
517      if (Content.ExecutionState == ExecutionState.Stopped) {
518        MessageBox.Show("Job cannot be updated once it stopped.", "HeuristicLab Hive Job Manager", MessageBoxButtons.OK, MessageBoxIcon.Information);
519        return;
520      }
521
522      var invoker = new Action<RefreshableJob>(HiveClient.UpdateJob);
523      invoker.BeginInvoke(Content, (ar) => {
524        try {
525          invoker.EndInvoke(ar);
526        } catch (Exception ex) {
527          ThreadPool.QueueUserWorkItem(delegate (object exception) { ErrorHandling.ShowErrorDialog(this, (Exception)exception); }, ex);
528        }
529      }, null);
530      UpdateSelectorDialog();
531    }
532
533    private void UnloadButton_Click(object sender, EventArgs e) {
534      Content.Unload();
535      runCollectionViewHost.Content = null;
536      stateLogViewHost.Content = null;
537      hiveExperimentPermissionListView.Content = null;
538      jobsTreeView.Content = null;
539
540      SetEnabledStateOfControls();
541    }
542
543    private void refreshPermissionsButton_Click(object sender, EventArgs e) {
544      if (this.Content.Job.Id == Guid.Empty) {
545        MessageBox.Show("You have to upload the Job first before you can share it.", "HeuristicLab Hive Job Manager", MessageBoxButtons.OK, MessageBoxIcon.Information);
546      } else {
547        hiveExperimentPermissionListView.Content = HiveClient.GetJobPermissions(this.Content.Job.Id);
548      }
549    }
550    #endregion
551
552    #region Helpers
553    private void SetEnabledStateOfExecutableButtons() {
554      if (Content == null) {
555        startButton.Enabled = pauseButton.Enabled = stopButton.Enabled = false;
556      } else {
557        startButton.Enabled = Content.IsControllable && Content.HiveTasks != null && Content.HiveTasks.Count > 0
558          && Content.Job.ProjectId != null && Content.Job.ProjectId != Guid.Empty && Content.Job.ResourceIds != null  && Content.Job.ResourceIds.Any()
559          && (Content.ExecutionState == ExecutionState.Prepared || Content.ExecutionState == ExecutionState.Paused) && !Content.IsProgressing;
560        pauseButton.Enabled = Content.IsControllable && Content.ExecutionState == ExecutionState.Started && !Content.IsProgressing;
561        stopButton.Enabled = Content.IsControllable && (Content.ExecutionState == ExecutionState.Started || Content.ExecutionState == ExecutionState.Paused) && !Content.IsProgressing;
562      }
563    }
564   
565    private Project GetProject(Guid projectId) {
566      return HiveServiceLocator.Instance.CallHiveService(s => s.GetProject(projectId));
567    }
568
569    private void UpdateSelectorDialog() {
570      if(hiveResourceSelectorDialog != null) {
571        hiveResourceSelectorDialog = null;
572        //hiveResourceSelectorDialog.JobId = Content.Job.Id;
573        //hiveResourceSelectorDialog.SelectedProjectId = Content.Job.ProjectId;
574        //hiveResourceSelectorDialog.SelectedResourceIds = Content.Job.ResourceIds;
575      }
576    }
577    #endregion
578
579    #region Drag & Drop
580    private void jobsTreeView_DragOver(object sender, DragEventArgs e) {
581      jobsTreeView_DragEnter(sender, e);
582    }
583
584    private void jobsTreeView_DragEnter(object sender, DragEventArgs e) {
585      e.Effect = DragDropEffects.None;
586      var obj = (IDeepCloneable)e.Data.GetData(Constants.DragDropDataFormat);
587
588      Type objType = obj.GetType();
589      if (ItemTask.IsTypeSupported(objType)) {
590        if (Content.Id != Guid.Empty) e.Effect = DragDropEffects.None;
591        else if ((e.KeyState & 32) == 32) e.Effect = DragDropEffects.Link;  // ALT key
592        else if (e.AllowedEffect.HasFlag(DragDropEffects.Copy)) e.Effect = DragDropEffects.Copy;
593      }
594    }
595
596    private void jobsTreeView_DragDrop(object sender, DragEventArgs e) {
597      if (e.Effect != DragDropEffects.None) {
598        var obj = (IItem)e.Data.GetData(Constants.DragDropDataFormat);
599
600        IItem newObj = null;
601        if (e.Effect.HasFlag(DragDropEffects.Copy)) {
602          newObj = (IItem)obj.Clone();
603        } else {
604          newObj = obj;
605        }
606
607        //IOptimizer and IExecutables need some special care
608        if (newObj is IOptimizer) {
609          ((IOptimizer)newObj).Runs.Clear();
610        }
611        if (newObj is IExecutable) {
612          IExecutable exec = (IExecutable)newObj;
613          if (exec.ExecutionState != ExecutionState.Prepared) {
614            exec.Prepare();
615          }
616        }
617
618        ItemTask hiveTask = ItemTask.GetItemTaskForItem(newObj);
619        Content.HiveTasks.Add(hiveTask.CreateHiveTask());
620      }
621    }
622    #endregion
623
624    private void tabControl_SelectedIndexChanged(object sender, EventArgs e) {
625      if (tabControl.SelectedTab == permissionTabPage) {
626        if (!Content.IsSharable) {
627          MessageBox.Show("Unable to load permissions. You have insufficient access privileges.", "HeuristicLab Hive Job Manager", MessageBoxButtons.OK, MessageBoxIcon.Information);
628          tabControl.SelectedTab = tasksTabPage;
629        }
630      }
631    }
632
633    private RunCollection GetAllRunsFromJob(RefreshableJob job) {
634      if (job != null) {
635        RunCollection runs = new RunCollection() { OptimizerName = job.ItemName };
636
637        foreach (HiveTask subTask in job.HiveTasks) {
638          if (subTask is OptimizerHiveTask) {
639            OptimizerHiveTask ohTask = subTask as OptimizerHiveTask;
640            ohTask.ExecuteReadActionOnItemTask(new Action(delegate () {
641              runs.AddRange(ohTask.ItemTask.Item.Runs);
642            }));
643          }
644        }
645        return runs;
646      } else {
647        return null;
648      }
649    }
650
651  }
652}
Note: See TracBrowser for help on using the repository browser.