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, 18 months ago

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

File size: 18.2 KB
Line 
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;
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 Dictionary<Guid, HashSet<Project>> projectAncestors = new Dictionary<Guid, HashSet<Project>>();
54    private readonly Dictionary<Guid, HashSet<Project>> projectDescendants = new Dictionary<Guid, HashSet<Project>>();
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>>();
57
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
62
63    private HashSet<Resource> projectExclusiveResources = new HashSet<Resource>();
64    private TreeNode ungroupedGroupNode;
65
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();
83        newAssignedResources.Clear();
84        includedResources.Clear();
85        resourceAncestors.Clear();
86        treeView.Nodes.Clear();
87        detailsViewHost.Content = null;
88      } else {
89        UpdateProjectGenealogy();
90        UpdateAssignedResources();
91        UpdateResourceGenealogy();
92        var top = BuildResourceTree(HiveAdminClient.Instance.Resources);
93        detailsViewHost.Content = top;
94      }
95    }
96
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    }
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) {
113      UpdateProjectGenealogy();
114      UpdateAssignedResources();
115      UpdateResourceGenealogy();
116      var top = BuildResourceTree(HiveAdminClient.Instance.Resources);
117      detailsViewHost.Content = top;
118    }
119
120    private async void inheritButton_Click(object sender, EventArgs e) {
121      await SecurityExceptionUtil.TryAsyncAndReportSecurityExceptions(
122        action: () => {
123          SetAssignedProjectResources(Content.Id, newAssignedResources.Select(x => x.Id), false, true, false);
124        });
125      UpdateResourceTree();
126    }
127
128    private async void saveButton_Click(object sender, EventArgs e) {
129      await SecurityExceptionUtil.TryAsyncAndReportSecurityExceptions(
130        action: () => {
131          SetAssignedProjectResources(Content.Id, newAssignedResources.Select(x => x.Id), false, false, false);
132        });
133      UpdateResourceTree();
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;
143      if (newIncludedResources.Contains(checkedResource) || checkedResource.Id == Guid.Empty || e.Node == ungroupedGroupNode) {
144        e.Cancel = true;
145      } else if (!HiveRoles.CheckAdminUserPermissions()) {
146          if (!projectAncestors[Content.Id].Any() || projectExclusiveResources.Contains(checkedResource)) {
147            e.Cancel = true;
148          }
149      }
150    }
151
152    private void treeView_AfterCheck(object sender, TreeViewEventArgs e) {
153      var checkedResource = (Resource)e.Node.Tag;
154      if (e.Node.Checked) {
155        newAssignedResources.Add(checkedResource);
156      } else {
157        newAssignedResources.Remove(checkedResource);
158      }
159
160      UpdateNewResourceTree();
161    }
162    #endregion
163
164    #region Helpers
165
166    private void UpdateResourceTree() {
167      UpdateAssignedResources();
168      UpdateResourceGenealogy();
169      var top = BuildResourceTree(HiveAdminClient.Instance.Resources);
170      detailsViewHost.Content = top;
171    }
172
173    private void UpdateNewResourceTree() {
174      UpdateNewAssignedResources();
175      UpdateNewIncludedResources();
176      var top = BuildResourceTree(HiveAdminClient.Instance.Resources);
177      detailsViewHost.Content = top;
178    }
179
180    private IEnumerable<Resource> GetAvailableResourcesForProjectAdministration(Guid projectId) {
181      projectExclusiveResources.Clear();
182      if (projectId == Guid.Empty) return Enumerable.Empty<Resource>();
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);
233    }
234
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
244    private void SetAssignedProjectResources(Guid projectId, IEnumerable<Guid> resourceIds, bool reassign, bool cascading, bool reassignCascading) {
245      if (projectId == null || resourceIds == null) return;
246      HiveServiceLocator.Instance.CallHiveService(s => {
247       s.SaveProjectResourceAssignments(projectId, resourceIds.ToList(), reassign, cascading, reassignCascading);
248      });
249    }
250
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
259    private void UpdateAssignedResources() {
260      assignedResources.Clear();
261      newAssignedResources.Clear();
262      foreach (var r in GetAssignedResourcesForProject(Content.Id)) {
263        assignedResources.Add(r);
264        newAssignedResources.Add(r);
265      }
266    }
267
268    private void UpdateNewIncludedResources() {
269      newIncludedResources.Clear();
270      foreach (var a in newAssignedResources) {
271        if (resourceDescendants.ContainsKey(a.Id)) {
272          foreach (var r in resourceDescendants[a.Id]) {
273            newIncludedResources.Add(r);
274          }
275        }
276      }
277    }
278
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
286      resources = GetAvailableResourcesForProjectAdministration(Content.Id);
287
288      var mainResources = new HashSet<Resource>(resources.OfType<SlaveGroup>().Where(x => x.ParentResourceId == null));
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);
292      var subResources = new HashSet<Resource>(resources.Except(mainResources));
293
294      var stack = new Stack<Resource>(mainResources.OrderByDescending(x => x.Name));
295      Resource top = null;
296
297      TreeNode currentNode = null;
298      Resource currentResource = null;
299
300      var addedAssignments = newAssignedResources.Except(assignedResources);
301      var removedAssignments = assignedResources.Except(newAssignedResources);
302      var addedIncludes = newIncludedResources.Except(includedResources);
303      var removedIncludes = includedResources.Except(newIncludedResources);
304
305      while (stack.Any()) {
306        if(top == null)  top = stack.Peek();
307        var newResource = stack.Pop();
308        var newNode = new TreeNode(newResource.Name) { Tag = newResource };
309
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)
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
324        if (newAssignedResources.Contains(newResource)) {
325          newNode.Checked = true;
326          if(!HiveRoles.CheckAdminUserPermissions()) {
327            if(!projectAncestors[Content.Id].Any() || projectExclusiveResources.Contains(newResource)) {
328              newNode.ForeColor = SystemColors.GrayText;
329              newNode.Text += IMMUTABLE_TAG;
330            }
331          }
332
333        } else if (newIncludedResources.Contains(newResource)) {
334          newNode.Checked = true;
335          newNode.ForeColor = SystemColors.GrayText;
336        }
337
338          if (includedResources.Contains(newResource) && newIncludedResources.Contains(newResource)) {
339          newNode.Text += INCLUDED_TAG;
340        } else if (addedIncludes.Contains(newResource)) {
341          newNode.BackColor = addedIncludeColor;
342          newNode.ForeColor = SystemColors.GrayText;
343          newNode.Text += ADDED_INCLUDE_TAG;
344        } else if (removedIncludes.Contains(newResource)) {
345          newNode.BackColor = removedIncludeColor;
346          newNode.Text += REMOVED_INCLUDE_TAG;
347        }
348
349        if (addedAssignments.Contains(newResource)) {
350          newNode.BackColor = addedAssignmentColor;
351          newNode.ForeColor = SystemColors.ControlText;
352          newNode.Text += ADDED_ASSIGNMENT_TAG;
353        } else if (removedAssignments.Contains(newResource)) {
354          newNode.BackColor = removedAssignmentColor;
355          newNode.ForeColor = SystemColors.ControlText;
356          newNode.Text += REMOVED_ASSIGNMENT_TAG;
357        }
358
359        if (newResource is Slave) {
360          newNode.ImageIndex = slaveImageIndex;
361        } else {
362          newNode.ImageIndex = slaveGroupImageIndex;
363
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);
369            }
370            currentNode = newNode;
371            currentResource = newResource;
372          }
373        }
374        newNode.SelectedImageIndex = newNode.ImageIndex;
375      }
376
377      var ungroupedSlaves = subResources.OfType<Slave>().OrderBy(x => x.Name);
378      if(ungroupedSlaves.Any()) {
379        ungroupedGroupNode = new TreeNode(UNGROUPED_GROUP_NAME) {
380          ForeColor = SystemColors.GrayText,
381          Tag = new SlaveGroup() {
382            Name = UNGROUPED_GROUP_NAME,
383            Description = UNGROUPED_GROUP_DESCRIPTION
384          }
385        };
386
387        foreach (var slave in ungroupedSlaves) {
388          var slaveNode = new TreeNode(slave.Name) { Tag = slave };
389          ungroupedGroupNode.Nodes.Add(slaveNode);
390        }
391        treeView.Nodes.Add(ungroupedGroupNode);
392      } else {
393        ungroupedGroupNode?.Nodes.Clear();
394      }
395
396      treeView.BeforeCheck += treeView_BeforeCheck;
397      treeView.AfterCheck += treeView_AfterCheck;
398      treeView.ExpandAll();
399
400      return top;
401    }
402
403    private void UpdateProjectGenealogy() {
404      projectAncestors.Clear();
405      projectDescendants.Clear();
406      var projects = HiveAdminClient.Instance.Projects;
407
408      foreach(var p in projects.Where(x => x.Id != Guid.Empty)) {
409        projectAncestors.Add(p.Id, new HashSet<Project>());
410        projectDescendants.Add(p.Id, new HashSet<Project>());
411      }
412
413      foreach (var p in projects.Where(x => x.Id != Guid.Empty)) {
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
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
468    #endregion
469  }
470}
Note: See TracBrowser for help on using the repository browser.