Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2839: implemented refreshing list of available (i.e. for non-admins assignable) resources depending on currently selected project

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