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

Last change on this file since 16209 was 16209, checked in by jzenisek, 12 months ago

#2839:

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