Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 15933 was 15933, checked in by jzenisek, 5 years ago

#2839: several fixes

  • rebuilt run in hive
  • adapted numeric selector (added FixedNumericUpDown.cs)
File size: 16.0 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
58    private HashSet<Resource> projectExclusiveResources = new HashSet<Resource>();
59    private TreeNode ungroupedGroupNode;
60
61    public new Project Content {
62      get { return (Project)base.Content; }
63      set { base.Content = value; }
64    }
65
66    public ProjectResourcesView() {
67      InitializeComponent();
68
69      treeView.ImageList.Images.Add(VSImageLibrary.MonitorLarge);
70      treeView.ImageList.Images.Add(VSImageLibrary.NetworkCenterLarge);
71    }
72
73    #region Overrides
74    protected override void OnContentChanged() {
75      base.OnContentChanged();
76      if (Content == null) {
77        assignedResources.Clear();
78        newAssignedResources.Clear();
79        includedResources.Clear();
80        treeView.Nodes.Clear();
81        detailsViewHost.Content = null;
82      } else {
83        UpdateAssignedResources();
84        UpdateIncludedResources();
85        var top = BuildResourceTree(HiveAdminClient.Instance.Resources);
86        detailsViewHost.Content = top;
87        detailsViewHost.Locked = true;
88      }
89    }
90
91    protected override void SetEnabledStateOfControls() {
92      base.SetEnabledStateOfControls();
93      bool enabled = Content != null && !Locked && !ReadOnly;
94
95      inheritButton.Enabled = enabled;
96      saveButton.Enabled = enabled;
97      treeView.Enabled = enabled;
98    }
99    #endregion
100
101    #region Event Handlers
102    private void ProjectResourcesView_Load(object sender, EventArgs e) {
103
104    }
105
106    private void refreshButton_Click(object sender, EventArgs e) {
107      HiveAdminClient.Instance.Refresh();
108      UpdateAssignedResources();
109      UpdateIncludedResources();
110      var top = BuildResourceTree(HiveAdminClient.Instance.Resources);
111      detailsViewHost.Content = top;
112    }
113
114    private async void inheritButton_Click(object sender, EventArgs e) {
115      await SecurityExceptionUtil.TryAsyncAndReportSecurityExceptions(
116        action: () => {
117          SetAssignedProjectResources(Content.Id, newAssignedResources.Select(x => x.Id), false, true, false);
118        });
119      UpdateResourceTree();
120    }
121
122    private async void saveButton_Click(object sender, EventArgs e) {
123      await SecurityExceptionUtil.TryAsyncAndReportSecurityExceptions(
124        action: () => {
125          SetAssignedProjectResources(Content.Id, newAssignedResources.Select(x => x.Id), false, false, false);
126        });
127      UpdateResourceTree();
128    }
129
130    private void treeView_AfterSelect(object sender, TreeViewEventArgs e) {
131      var selectedResource = (Resource)e.Node.Tag;
132      detailsViewHost.Content = selectedResource;
133    }
134
135    private void treeView_BeforeCheck(object sender, TreeViewCancelEventArgs e) {
136      var checkedResource = (Resource)e.Node.Tag;
137      if (newIncludedResources.Contains(checkedResource) || checkedResource.Id == Guid.Empty || e.Node == ungroupedGroupNode) {
138        e.Cancel = true;
139      } else if (!HiveRoles.CheckAdminUserPermissions()) {
140          if (!HiveAdminClient.Instance.GetAvailableProjectAncestors(Content.Id).Any() || projectExclusiveResources.Contains(checkedResource)) {
141            e.Cancel = true;
142          }
143      }
144    }
145
146    private void treeView_AfterCheck(object sender, TreeViewEventArgs e) {
147      var checkedResource = (Resource)e.Node.Tag;
148      if (e.Node.Checked) {
149        newAssignedResources.Add(checkedResource);
150      } else {
151        newAssignedResources.Remove(checkedResource);
152      }
153
154      UpdateNewResourceTree();
155    }
156    #endregion
157
158    #region Helpers
159
160    private void UpdateResourceTree() {
161      UpdateAssignedResources();
162      UpdateIncludedResources();
163
164      var top = BuildResourceTree(HiveAdminClient.Instance.Resources);
165      detailsViewHost.Content = top;
166    }
167
168    private void UpdateNewResourceTree() {
169      UpdateNewAssignedResources();
170      UpdateNewIncludedResources();
171      var top = BuildResourceTree(HiveAdminClient.Instance.Resources);
172      detailsViewHost.Content = top;
173    }
174
175    private IEnumerable<Resource> GetAvailableResourcesForProjectAdministration(Guid projectId) {
176      projectExclusiveResources.Clear();
177      if (projectId == Guid.Empty) return Enumerable.Empty<Resource>();
178      var resources = HiveAdminClient.Instance.Resources.Where(x => x.Id != Guid.Empty);
179      if (!resources.Any()) return resources;
180      if (IsAdmin()) return resources;
181
182      // get project specific assigned resources
183      var projectResources = resources.Where(x =>
184        HiveAdminClient.Instance.ProjectResourceAssignments
185          .Where(a => a.ProjectId == projectId)
186          .Select(a => a.ResourceId)
187        .Contains(x.Id));
188
189      // look up for assignments of ancestor projects
190      var projectIds = new HashSet<Guid>();
191      HiveClient.Instance.GetAvailableProjectAncestors(projectId).ToList().ForEach(x => projectIds.Add(x.Id));
192
193      var ancestorProjectResources = resources.Where(x =>
194        HiveAdminClient.Instance.ProjectResourceAssignments
195          .Where(a => projectIds.Contains(a.ProjectId))
196          .Select(a => a.ResourceId)
197        .Contains(x.Id));
198
199      // look down for included resources of ancestor projects
200      HashSet<Resource> availableResources = new HashSet<Resource>(ancestorProjectResources);
201      foreach (var r in ancestorProjectResources) {
202        foreach(var d in HiveAdminClient.Instance.GetAvailableResourceDescendants(r.Id)) {
203          availableResources.Add(d);
204        }
205      }
206
207      // determine resources, which are exclusively assigned to the currently selected project
208      projectResources
209        .Except(availableResources)
210        .ToList()
211        .ForEach(x => projectExclusiveResources.Add(x));
212
213      // look down for included resources of currently selected project
214      if (projectExclusiveResources.Any()) {
215        foreach (var r in projectExclusiveResources.ToArray()) {
216          foreach (var d in HiveAdminClient.Instance.GetAvailableResourceDescendants(r.Id)) {
217            projectExclusiveResources.Add(d);
218          } 
219        }
220      }
221
222      return availableResources.Union(projectExclusiveResources);
223    }
224
225    private IEnumerable<Resource> GetAssignedResourcesForProject(Guid projectId) {
226      if (projectId == Guid.Empty) return Enumerable.Empty<Resource>();
227      return HiveAdminClient.Instance.Resources.Where(x =>
228        HiveAdminClient.Instance.ProjectResourceAssignments
229          .Where(a => a.ProjectId == projectId)
230          .Select(a => a.ResourceId)
231        .Contains(x.Id));
232    }
233
234    private void SetAssignedProjectResources(Guid projectId, IEnumerable<Guid> resourceIds, bool reassign, bool cascading, bool reassignCascading) {
235      if (projectId == null || resourceIds == null) return;
236      HiveServiceLocator.Instance.CallHiveService(s => {
237       s.SaveProjectResourceAssignments(projectId, resourceIds.ToList(), reassign, cascading, reassignCascading);
238      });
239    }
240
241    private void UpdateNewAssignedResources() {
242      for(int i = newAssignedResources.Count -1; i >= 0; i--) {
243        if(newAssignedResources.Intersect(HiveAdminClient.Instance.GetAvailableResourceAncestors(newAssignedResources.ElementAt(i).Id)).Any()) {
244          newAssignedResources.Remove(newAssignedResources.ElementAt(i));
245        }
246      }
247    }
248
249    private void UpdateAssignedResources() {
250      assignedResources.Clear();
251      newAssignedResources.Clear();
252      foreach (var r in GetAssignedResourcesForProject(Content.Id)) {
253        assignedResources.Add(r);
254        newAssignedResources.Add(r);
255      }
256    }
257
258    private void UpdateIncludedResources() {
259      includedResources.Clear();
260      newIncludedResources.Clear();
261      foreach (var a in assignedResources) {
262        foreach (var r in HiveAdminClient.Instance.GetAvailableResourceDescendants(a.Id)) {
263          includedResources.Add(r);
264          newIncludedResources.Add(r);
265        }
266      }
267    }
268
269    private void UpdateNewIncludedResources() {
270      newIncludedResources.Clear();
271      foreach (var a in newAssignedResources) {
272        foreach (var r in HiveAdminClient.Instance.GetAvailableResourceDescendants(a.Id)) {
273          newIncludedResources.Add(r);
274        }
275      }
276    }
277
278    private Resource BuildResourceTree(IEnumerable<Resource> resources) {
279      treeView.Nodes.Clear();
280      if (!resources.Any()) return null;
281
282      treeView.BeforeCheck -= treeView_BeforeCheck;
283      treeView.AfterCheck -= treeView_AfterCheck;
284
285      resources = GetAvailableResourcesForProjectAdministration(Content.Id);
286
287      var mainResources = new HashSet<Resource>(resources.OfType<SlaveGroup>().Where(x => x.ParentResourceId == null));
288      var parentedMainResources = new HashSet<Resource>(resources.OfType<SlaveGroup>()
289        .Where(x => x.ParentResourceId.HasValue && !resources.Select(y => y.Id).Contains(x.ParentResourceId.Value)));
290      mainResources.UnionWith(parentedMainResources);
291      var subResources = new HashSet<Resource>(resources.Except(mainResources));
292
293      var stack = new Stack<Resource>(mainResources.OrderByDescending(x => x.Name));
294      Resource top = null;
295
296      TreeNode currentNode = null;
297      Resource currentResource = null;
298
299      var addedAssignments = newAssignedResources.Except(assignedResources);
300      var removedAssignments = assignedResources.Except(newAssignedResources);
301      var addedIncludes = newIncludedResources.Except(includedResources);
302      var removedIncludes = includedResources.Except(newIncludedResources);
303
304      while (stack.Any()) {
305        if(top == null)  top = stack.Peek();
306        var newResource = stack.Pop();
307        var newNode = new TreeNode(newResource.Name) { Tag = newResource };
308
309        // search for parent node of newNode and save in currentNode
310        // necessary since newNodes (stack top items) might be siblings
311        // or grand..grandparents of previous node (currentNode)
312        while (currentNode != null && newResource.ParentResourceId != currentResource.Id) {
313          currentNode = currentNode.Parent;
314          currentResource = currentNode == null ? null : (Resource)currentNode.Tag;
315        }
316
317        if (currentNode == null) {
318          treeView.Nodes.Add(newNode);
319        } else {
320          currentNode.Nodes.Add(newNode);
321        }
322
323        if (newAssignedResources.Contains(newResource)) {
324          newNode.Checked = true;
325          if(!HiveRoles.CheckAdminUserPermissions()) {
326            if (!HiveAdminClient.Instance.GetAvailableProjectAncestors(Content.Id).Any()
327              || 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 bool IsAdmin() {
404      return HiveRoles.CheckAdminUserPermissions();
405    }
406
407    #endregion
408  }
409}
Note: See TracBrowser for help on using the repository browser.