Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2839_HiveProjectManagement/HeuristicLab.Clients.Hive.Administrator/3.3/Views/ProjectResourcesView.cs @ 17713

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

#2839: worked on hive project management

  • removed usage of null-conditional operator
File size: 18.5 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.Collections.Generic;
24using System.Drawing;
25using System.Linq;
26using System.Windows.Forms;
27using HeuristicLab.Clients.Access;
28using HeuristicLab.Common.Resources;
29using HeuristicLab.Core.Views;
30using HeuristicLab.MainForm;
31using System.Collections;
32
33namespace HeuristicLab.Clients.Hive.Administrator.Views {
34  [View("ProjectView")]
35  [Content(typeof(Project), IsDefaultView = false)]
36  public partial class ProjectResourcesView : ItemView {
37    private const int slaveImageIndex = 0;
38    private const int slaveGroupImageIndex = 1;
39    public const string UNGROUPED_GROUP_NAME = "UNGROUPED";
40    public const string UNGROUPED_GROUP_DESCRIPTION = "Contains slaves that are not assigned to any group.";
41    public const string IMMUTABLE_TAG = " [assigned, immutable]";
42    public const string INCLUDED_TAG = " [included]";
43    public const string ADDED_ASSIGNMENT_TAG = " [added assignment]";
44    public const string REMOVED_ASSIGNMENT_TAG = " [removed assignment]";
45    public const string ADDED_INCLUDE_TAG = " [added include]";
46    public const string REMOVED_INCLUDE_TAG = " [removed include]";
47
48    private readonly HashSet<Resource> assignedResources = new HashSet<Resource>();
49    private readonly HashSet<Resource> newAssignedResources = new HashSet<Resource>();
50    private readonly HashSet<Resource> includedResources = new HashSet<Resource>();
51    private readonly HashSet<Resource> newIncludedResources = new HashSet<Resource>();
52
53    private readonly Color addedAssignmentColor = Color.FromArgb(255, 87, 191, 193); // #57bfc1
54    private readonly Color removedAssignmentColor = Color.FromArgb(255, 236, 159, 72); // #ec9f48
55    private readonly Color addedIncludeColor = Color.FromArgb(25, 169, 221, 221); // #a9dddd
56    private readonly Color removedIncludeColor = Color.FromArgb(25, 249, 210, 145); // #f9d291
57    private readonly Color selectedBackColor = Color.DodgerBlue;
58    private readonly Color selectedForeColor = Color.White;
59    private readonly Color grayTextColor = SystemColors.GrayText;
60
61    private HashSet<Resource> projectExclusiveResources = new HashSet<Resource>();
62    private TreeNode ungroupedGroupNode;
63
64    public new Project Content {
65      get { return (Project)base.Content; }
66      set { base.Content = value; }
67    }
68
69    public ProjectResourcesView() {
70      InitializeComponent();
71
72      treeView.ImageList.Images.Add(VSImageLibrary.MonitorLarge);
73      treeView.ImageList.Images.Add(VSImageLibrary.NetworkCenterLarge);
74    }
75
76    #region Overrides
77    protected override void OnContentChanged() {
78      base.OnContentChanged();
79      if (Content == null) {
80        assignedResources.Clear();
81        newAssignedResources.Clear();
82        includedResources.Clear();
83        treeView.Nodes.Clear();
84        detailsViewHost.Content = null;
85      } else {
86        UpdateAssignedResources();
87        UpdateIncludedResources();
88        var top = BuildResourceTree();
89        detailsViewHost.Content = top;
90        detailsViewHost.Locked = true;
91      }
92    }
93
94    protected override void SetEnabledStateOfControls() {
95      base.SetEnabledStateOfControls();
96      bool enabled = Content != null && !Locked && !ReadOnly;
97
98      inheritButton.Enabled = enabled;
99      saveButton.Enabled = enabled;
100      treeView.Enabled = enabled;
101    }
102    #endregion
103
104    #region Event Handlers
105    private void ProjectResourcesView_Load(object sender, EventArgs e) {
106
107    }
108
109    private void refreshButton_Click(object sender, EventArgs e) {
110      HiveAdminClient.Instance.Refresh();
111      UpdateAssignedResources();
112      UpdateIncludedResources();
113      var top = BuildResourceTree();
114      detailsViewHost.Content = top;
115    }
116
117    private async void inheritButton_Click(object sender, EventArgs e) {
118      await SecurityExceptionUtil.TryAsyncAndReportSecurityExceptions(
119        action: () => {
120          SetAssignedProjectResources(Content.Id, newAssignedResources.Select(x => x.Id), false, true, false);
121        });
122      HiveAdminClient.Instance.Refresh();
123      UpdateResourceTree();
124    }
125
126    private async void saveButton_Click(object sender, EventArgs e) {
127      await SecurityExceptionUtil.TryAsyncAndReportSecurityExceptions(
128        action: () => {
129          SetAssignedProjectResources(Content.Id, newAssignedResources.Select(x => x.Id), false, false, false);
130        });
131      HiveAdminClient.Instance.Refresh();
132      UpdateResourceTree();
133    }
134
135    private void treeView_BeforeSelect(object sender, TreeViewCancelEventArgs e) {
136      if (e.Node == null || e.Node == ungroupedGroupNode)
137        e.Cancel = true;
138
139      var selectedResource = (Resource)e.Node.Tag;
140      if(HiveAdminClient.Instance.DisabledParentResources.Contains(selectedResource))
141        e.Cancel = true;
142    }
143
144    private void treeView_AfterSelect(object sender, TreeViewEventArgs e) {
145      var selectedResource = (Resource)e.Node.Tag;
146      detailsViewHost.Content = selectedResource;
147    }
148
149    private void treeView_BeforeCheck(object sender, TreeViewCancelEventArgs e) {
150      if (e.Node == null || e.Node == ungroupedGroupNode) {
151        e.Cancel = true;
152        return;
153      }
154       
155      var checkedResource = (Resource)e.Node.Tag;
156      if (checkedResource == null
157        || checkedResource.Id == Guid.Empty
158        || HiveAdminClient.Instance.DisabledParentResources.Contains(checkedResource)
159        || newIncludedResources.Contains(checkedResource)) {
160        e.Cancel = true;
161      } else if (!IsAdmin()) {
162          if (!HiveAdminClient.Instance.CheckOwnershipOfParentProject(Content, UserInformation.Instance.User.Id)
163            || !HiveAdminClient.Instance.GetAvailableProjectAncestors(Content.Id).Any()
164            || projectExclusiveResources.Contains(checkedResource)) {
165            e.Cancel = true;
166          }
167      }
168    }
169
170    private void treeView_AfterCheck(object sender, TreeViewEventArgs e) {
171      var checkedResource = (Resource)e.Node.Tag;
172      if (e.Node.Checked) {
173        newAssignedResources.Add(checkedResource);
174      } else {
175        newAssignedResources.Remove(checkedResource);
176      }
177
178      UpdateNewResourceTree();
179    }
180    #endregion
181
182    #region Helpers
183
184    private void UpdateResourceTree() {
185      UpdateAssignedResources();
186      UpdateIncludedResources();
187
188      var top = BuildResourceTree();
189      detailsViewHost.Content = top;
190    }
191
192    private void UpdateNewResourceTree() {
193      UpdateNewAssignedResources();
194      UpdateNewIncludedResources();
195      var top = BuildResourceTree();
196      detailsViewHost.Content = top;
197    }
198
199    private IEnumerable<Resource> GetAvailableResourcesForProjectAdministration(Guid projectId) {
200      projectExclusiveResources.Clear();
201      if (projectId == Guid.Empty) return Enumerable.Empty<Resource>();
202      var resources = HiveAdminClient.Instance.Resources.Where(x => x.Id != Guid.Empty);
203      if (!resources.Any()) return resources;
204      if (IsAdmin()) return resources;
205
206      // get project specific assigned resources
207      var projectResources = resources.Where(x =>
208        HiveAdminClient.Instance.ProjectResourceAssignments
209          .Where(a => a.ProjectId == projectId)
210          .Select(a => a.ResourceId)
211        .Contains(x.Id));
212
213      // look up for assignments of ancestor projects
214      var projectIds = new HashSet<Guid>();
215      HiveAdminClient.Instance.GetAvailableProjectAncestors(projectId).ToList().ForEach(x => projectIds.Add(x.Id));
216
217      var ancestorProjectResources = resources.Where(x =>
218        HiveAdminClient.Instance.ProjectResourceAssignments
219          .Where(a => projectIds.Contains(a.ProjectId))
220          .Select(a => a.ResourceId)
221        .Contains(x.Id));
222
223      // look down for included resources of ancestor projects
224      HashSet<Resource> availableResources = new HashSet<Resource>(ancestorProjectResources);
225      foreach (var r in ancestorProjectResources) {
226        foreach(var d in HiveAdminClient.Instance.GetAvailableResourceDescendants(r.Id)) {
227          availableResources.Add(d);
228        }
229      }
230
231      // determine resources, which are exclusively assigned to the currently selected project
232      projectResources
233        .Except(availableResources)
234        .ToList()
235        .ForEach(x => projectExclusiveResources.Add(x));
236
237      // look down for included resources of currently selected project
238      if (projectExclusiveResources.Any()) {
239        foreach (var r in projectExclusiveResources.ToArray()) {
240          foreach (var d in HiveAdminClient.Instance.GetAvailableResourceDescendants(r.Id)) {
241            projectExclusiveResources.Add(d);
242          } 
243        }
244      }
245
246      return availableResources.Union(projectExclusiveResources);
247    }
248
249    private IEnumerable<Resource> GetAssignedResourcesForProject(Guid projectId) {
250      if (projectId == Guid.Empty) return Enumerable.Empty<Resource>();
251      return HiveAdminClient.Instance.Resources.Where(x =>
252        HiveAdminClient.Instance.ProjectResourceAssignments
253          .Where(a => a.ProjectId == projectId)
254          .Select(a => a.ResourceId)
255        .Contains(x.Id));
256    }
257
258    private void SetAssignedProjectResources(Guid projectId, IEnumerable<Guid> resourceIds, bool reassign, bool cascading, bool reassignCascading) {
259      if (projectId == null || resourceIds == null) return;
260      HiveServiceLocator.Instance.CallHiveService(s => {
261       s.SaveProjectResourceAssignments(projectId, resourceIds.ToList(), reassign, cascading, reassignCascading);
262      });
263    }
264
265    private void UpdateNewAssignedResources() {
266      for(int i = newAssignedResources.Count -1; i >= 0; i--) {
267        if(newAssignedResources.Intersect(HiveAdminClient.Instance.GetAvailableResourceAncestors(newAssignedResources.ElementAt(i).Id)).Any()) {
268          newAssignedResources.Remove(newAssignedResources.ElementAt(i));
269        }
270      }
271    }
272
273    private void UpdateAssignedResources() {
274      assignedResources.Clear();
275      newAssignedResources.Clear();
276      foreach (var r in GetAssignedResourcesForProject(Content.Id)) {
277        assignedResources.Add(r);
278        newAssignedResources.Add(r);
279      }
280    }
281
282    private void UpdateIncludedResources() {
283      includedResources.Clear();
284      newIncludedResources.Clear();
285      foreach (var a in assignedResources) {
286        foreach (var r in HiveAdminClient.Instance.GetAvailableResourceDescendants(a.Id)) {
287          includedResources.Add(r);
288          newIncludedResources.Add(r);
289        }
290      }
291    }
292
293    private void UpdateNewIncludedResources() {
294      newIncludedResources.Clear();
295      foreach (var a in newAssignedResources) {
296        foreach (var r in HiveAdminClient.Instance.GetAvailableResourceDescendants(a.Id)) {
297          newIncludedResources.Add(r);
298        }
299      }
300    }
301
302    private Resource BuildResourceTree() {
303      treeView.Nodes.Clear();
304
305      treeView.BeforeCheck -= treeView_BeforeCheck;
306      treeView.AfterCheck -= treeView_AfterCheck;
307
308      var resources = GetAvailableResourcesForProjectAdministration(Content.Id);
309
310      var disabledParentResources = HiveAdminClient.Instance.DisabledParentResources;
311      var mainResources = new HashSet<Resource>(resources.OfType<SlaveGroup>().Where(x => x.ParentResourceId == null));
312      //var parentedMainResources = new HashSet<Resource>(resources.OfType<SlaveGroup>()
313      //  .Where(x => x.ParentResourceId.HasValue && !resources.Select(y => y.Id).Contains(x.ParentResourceId.Value)));
314      //mainResources.UnionWith(parentedMainResources);
315      var mainDisabledParentResources = new HashSet<Resource>(disabledParentResources.Where(x => x.ParentResourceId == null || x.ParentResourceId == Guid.Empty));
316      mainResources.UnionWith(mainDisabledParentResources);
317      var subResources = new HashSet<Resource>(resources.Union(disabledParentResources).Except(mainResources).OrderByDescending(x => x.Name));
318
319      var stack = new Stack<Resource>(mainResources.OrderByDescending(x => x.Name));
320     
321      Resource top = null;
322      //bool nodeSelected = false;
323      if (detailsViewHost != null && detailsViewHost.Content != null && detailsViewHost.Content is Resource) {
324        var resourceId = ((Resource)detailsViewHost.Content).Id;
325        top = resources.Where(x => x.Id == resourceId).FirstOrDefault();
326      }
327     
328
329      TreeNode currentNode = null;
330      Resource currentResource = null;
331
332      var addedAssignments = newAssignedResources.Except(assignedResources);
333      var removedAssignments = assignedResources.Except(newAssignedResources);
334      var addedIncludes = newIncludedResources.Except(includedResources);
335      var removedIncludes = includedResources.Except(newIncludedResources);
336
337      while (stack.Any()) {
338        var newResource = stack.Pop();
339        var newNode = new TreeNode(newResource.Name) { Tag = newResource };
340
341        if(top == null && !disabledParentResources.Contains(newResource)) {
342          top = newResource;
343        }
344
345        //if(!nodeSelected && top != null && newResource.Id == top.Id) {
346        //  newNode.BackColor = selectedBackColor;
347        //  newNode.ForeColor = selectedForeColor;
348        //  nodeSelected = true;
349        //}
350
351        // search for parent node of newNode and save in currentNode
352        // necessary since newNodes (stack top items) might be siblings
353        // or grand..grandparents of previous node (currentNode)
354        while (currentNode != null && newResource.ParentResourceId != currentResource.Id) {
355          currentNode = currentNode.Parent;
356          currentResource = currentNode == null ? null : (Resource)currentNode.Tag;
357        }
358
359        if (currentNode == null) {
360          treeView.Nodes.Add(newNode);
361        } else {
362          currentNode.Nodes.Add(newNode);
363        }
364
365        if (disabledParentResources.Contains(newResource)) {
366          newNode.Checked = false;
367          newNode.ForeColor = grayTextColor;
368        } else if (newAssignedResources.Contains(newResource)) {
369          newNode.Checked = true;
370          if(!HiveRoles.CheckAdminUserPermissions()) {
371            if (!HiveAdminClient.Instance.CheckOwnershipOfParentProject(Content, UserInformation.Instance.User.Id)
372              || !HiveAdminClient.Instance.GetAvailableProjectAncestors(Content.Id).Any()
373              || projectExclusiveResources.Contains(newResource)) {
374              newNode.ForeColor = SystemColors.GrayText;
375              newNode.Text += IMMUTABLE_TAG;
376            }
377          }
378
379        } else if (newIncludedResources.Contains(newResource)) {
380          newNode.Checked = true;
381          newNode.ForeColor = SystemColors.GrayText;
382        }
383
384          if (includedResources.Contains(newResource) && newIncludedResources.Contains(newResource)) {
385          newNode.Text += INCLUDED_TAG;
386        } else if (addedIncludes.Contains(newResource)) {
387          newNode.BackColor = addedIncludeColor;
388          newNode.ForeColor = SystemColors.GrayText;
389          newNode.Text += ADDED_INCLUDE_TAG;
390        } else if (removedIncludes.Contains(newResource)) {
391          newNode.BackColor = removedIncludeColor;
392          newNode.Text += REMOVED_INCLUDE_TAG;
393        }
394
395        if (addedAssignments.Contains(newResource)) {
396          newNode.BackColor = addedAssignmentColor;
397          newNode.ForeColor = SystemColors.ControlText;
398          newNode.Text += ADDED_ASSIGNMENT_TAG;
399        } else if (removedAssignments.Contains(newResource)) {
400          newNode.BackColor = removedAssignmentColor;
401          newNode.ForeColor = SystemColors.ControlText;
402          newNode.Text += REMOVED_ASSIGNMENT_TAG;
403        }
404
405        if (newResource is Slave) {
406          newNode.ImageIndex = slaveImageIndex;
407        } else {
408          newNode.ImageIndex = slaveGroupImageIndex;
409
410          var childResources = subResources.Where(x => x.ParentResourceId == newResource.Id);
411          if (childResources.Any()) {
412            foreach (var resource in childResources.OrderByDescending(x => x.Name)) {
413              subResources.Remove(resource);
414              stack.Push(resource);
415            }
416            currentNode = newNode;
417            currentResource = newResource;
418          }
419        }
420        newNode.SelectedImageIndex = newNode.ImageIndex;
421      }
422
423      var ungroupedSlaves = subResources.OfType<Slave>().OrderBy(x => x.Name);
424      if(ungroupedSlaves.Any()) {
425        ungroupedGroupNode = new TreeNode(UNGROUPED_GROUP_NAME) {
426          ForeColor = SystemColors.GrayText,
427          Tag = new SlaveGroup() {
428            Name = UNGROUPED_GROUP_NAME,
429            Description = UNGROUPED_GROUP_DESCRIPTION
430          }
431        };
432
433        foreach (var slave in ungroupedSlaves) {
434          var slaveNode = new TreeNode(slave.Name) { Tag = slave };
435          ungroupedGroupNode.Nodes.Add(slaveNode);
436        }
437        treeView.Nodes.Add(ungroupedGroupNode);
438      } else if (ungroupedGroupNode != null) {
439        ungroupedGroupNode.Nodes.Clear();
440      }
441
442      treeView.BeforeCheck += treeView_BeforeCheck;
443      treeView.AfterCheck += treeView_AfterCheck;
444     
445      ExpandResourceNodesOfInterest(treeView.Nodes);
446
447      return top;
448    }
449
450    private void ExpandResourceNodesOfInterest(TreeNodeCollection nodes) {
451      foreach (TreeNode n in nodes) {
452        Resource r = (Resource)n.Tag;
453        if (n.Nodes.Count > 0) {
454          if (HiveAdminClient.Instance.GetAvailableResourceDescendants(r.Id).OfType<SlaveGroup>().Any()) {
455            n.Expand();
456            ExpandResourceNodesOfInterest(n.Nodes);
457          } else {
458            n.Collapse();
459          }
460        } else {
461          n.Collapse();
462        }
463      }
464    }
465
466    private bool IsAdmin() {
467      return HiveRoles.CheckAdminUserPermissions();
468    }
469
470    #endregion
471  }
472}
Note: See TracBrowser for help on using the repository browser.