Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2839_HiveProjectManagement/HeuristicLab.Clients.Hive.JobManager/3.3/Views/RefreshableHiveJobView.cs @ 15995

Last change on this file since 15995 was 15992, checked in by jzenisek, 6 years ago

#2839: fixed couple of minor issues

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