source: branches/HiveProjectManagement/HeuristicLab.Clients.Hive.Administrator/3.3/Views/ProjectsView.cs @ 15658

Last change on this file since 15658 was 15658, checked in by jzenisek, 3 years ago

#2839

  • worked on (restricted) accessibility of hive's administration area for non-admin roles
  • adapted HiveClient & HiveAdminClient entity loading (client- & service-side)
File size: 15.7 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.ComponentModel;
25using System.Drawing;
26using System.Linq;
27using System.Windows.Forms;
28using HeuristicLab.Clients.Access;
29using HeuristicLab.Clients.Hive.Views;
30using HeuristicLab.Collections;
31using HeuristicLab.Common.Resources;
32using HeuristicLab.Core;
33using HeuristicLab.Core.Views;
34using HeuristicLab.MainForm;
35
36namespace HeuristicLab.Clients.Hive.Administrator.Views {
37  [View("Projects View")]
38  [Content(typeof(IItemList<Project>), false)]
39  public partial class ProjectsView : ItemView, IDisposable {
40    private const int greenFlagImageIndex = 0;
41    private const int redFlagImageIndex = 1;
42    private readonly Color changedColor = Color.FromArgb(255, 87, 191, 193); // #57bfc1
43    private readonly Color selectedColor = Color.FromArgb(255, 240, 194, 59); // #f0c23b
44
45    private readonly object locker = new object();
46
47    private Project selectedProject = null;
48
49    public new IItemList<Project> Content {
50      get { return (IItemList<Project>)base.Content; }
51      set { base.Content = value; }
52    }
53
54    public ProjectsView() {
55      InitializeComponent();
56
57      projectsTreeView.ImageList.Images.Add(VSImageLibrary.FlagGreen);
58      projectsTreeView.ImageList.Images.Add(VSImageLibrary.FlagRed);
59
60      HiveAdminClient.Instance.Refreshing += HiveAdminClient_Instance_Refreshing;
61      HiveAdminClient.Instance.Refreshed += HiveAdminClient_Instance_Refreshed;
62      AccessClient.Instance.Refreshing += AccessClient_Instance_Refreshing;
63      AccessClient.Instance.Refreshed += AccessClient_Instance_Refreshed;
64    }
65
66    #region Overrides
67    protected override void OnClosing(FormClosingEventArgs e) {
68      AccessClient.Instance.Refreshed -= AccessClient_Instance_Refreshed;
69      AccessClient.Instance.Refreshing -= AccessClient_Instance_Refreshing;
70      HiveAdminClient.Instance.Refreshed -= HiveAdminClient_Instance_Refreshed;
71      HiveAdminClient.Instance.Refreshing -= HiveAdminClient_Instance_Refreshing;
72      base.OnClosing(e);
73    }
74
75    protected override void RegisterContentEvents() {
76      base.RegisterContentEvents();
77      Content.ItemsAdded += Content_ItemsAdded;
78      Content.ItemsRemoved += Content_ItemsRemoved;
79    }
80
81    protected override void DeregisterContentEvents() {
82      Content.ItemsRemoved -= Content_ItemsRemoved;
83      Content.ItemsAdded -= Content_ItemsAdded;
84      base.DeregisterContentEvents();
85    }
86
87    protected override void OnContentChanged() {
88      base.OnContentChanged();
89      if (Content == null) {
90        projectsTreeView.Nodes.Clear();
91        projectView.Content = null;
92        projectPermissionsView.Content = null;
93        projectResourcesView.Content = null;
94      } else {
95        var top = BuildProjectTree(Content);
96        projectView.Content = top;
97        projectPermissionsView.Content = top;
98        projectResourcesView.Content = top;
99      }
100    }
101
102    protected override void SetEnabledStateOfControls() {
103      base.SetEnabledStateOfControls();
104      bool enabled = Content != null && !ReadOnly;
105      refreshButton.Enabled = enabled;
106      addButton.Enabled = enabled;
107      removeButton.Enabled = enabled;
108      saveProjectButton.Enabled = enabled;
109      projectView.Enabled = enabled;
110      projectPermissionsView.Enabled = enabled;
111      projectResourcesView.Enabled = enabled;
112    }
113    #endregion
114
115    #region Event Handlers
116    private void Content_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IndexedItem<Project>> e) {
117      if (InvokeRequired) Invoke((Action<object, CollectionItemsChangedEventArgs<IndexedItem<Project>>>)Content_ItemsAdded, sender, e);
118      else {
119        OnContentChanged();
120      }
121    }
122
123    private void Content_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<Project>> e) {
124      if (InvokeRequired) Invoke((Action<object, CollectionItemsChangedEventArgs<IndexedItem<Project>>>)Content_ItemsRemoved, sender, e);
125      else {
126        OnContentChanged();
127      }
128    }
129
130    private void ProjectViewContent_PropertyChanged(object sender, PropertyChangedEventArgs e) {
131      if (InvokeRequired) Invoke((Action<object, PropertyChangedEventArgs>)ProjectViewContent_PropertyChanged, sender, e);
132      else {
133        OnContentChanged();
134      }
135    }
136
137    private void HiveAdminClient_Instance_Refreshing(object sender, EventArgs e) {
138      if (InvokeRequired) Invoke((Action<object, EventArgs>)HiveAdminClient_Instance_Refreshing, sender, e);
139      else {
140        var mainForm = MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>();
141        mainForm.AddOperationProgressToView(this, "Refreshing ...");
142        SetEnabledStateOfControls();
143      }
144    }
145
146    private void HiveAdminClient_Instance_Refreshed(object sender, EventArgs e) {
147      if (InvokeRequired) Invoke((Action<object, EventArgs>)HiveAdminClient_Instance_Refreshed, sender, e);
148      else {
149        var mainForm = MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>();
150        mainForm.RemoveOperationProgressFromView(this);
151        SetEnabledStateOfControls();
152      }
153    }
154
155    private void AccessClient_Instance_Refreshing(object sender, EventArgs e) {
156      if (InvokeRequired) Invoke((Action<object, EventArgs>)AccessClient_Instance_Refreshing, sender, e);
157      else {
158        var mainForm = MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>();
159        mainForm.AddOperationProgressToView(this, "Refreshing ...");
160        SetEnabledStateOfControls();
161      }
162    }
163
164    private void AccessClient_Instance_Refreshed(object sender, EventArgs e) {
165      if (InvokeRequired) Invoke((Action<object, EventArgs>)AccessClient_Instance_Refreshed, sender, e);
166      else {
167        var mainForm = MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>();
168        mainForm.RemoveOperationProgressFromView(this);
169        SetEnabledStateOfControls();
170      }
171    }
172
173    private async void ProjectsView_Load(object sender, EventArgs e) {
174      await SecurityExceptionUtil.TryAsyncAndReportSecurityExceptions(
175        action: () => UpdateProjects(),
176        finallyCallback: () => Content = HiveAdminClient.Instance.Projects);
177    }
178
179    private async void refreshButton_Click(object sender, EventArgs e) {
180      lock (locker) {
181        if (!refreshButton.Enabled) return;
182        refreshButton.Enabled = false;
183      }
184
185      await SecurityExceptionUtil.TryAsyncAndReportSecurityExceptions(
186        action: () => UpdateProjects(),
187        finallyCallback: () => {
188          Content = HiveAdminClient.Instance.Projects;
189          refreshButton.Enabled = true;
190        });
191    }
192
193    private void addButton_Click(object sender, EventArgs e) {
194      Guid? parentProjectId = null;
195      if (selectedProject != null) parentProjectId = selectedProject.Id;
196      var project = new Project {
197        Name = "New Project",
198        OwnerUserId = UserInformation.Instance.User.Id,
199        ParentProjectId = parentProjectId
200      };
201      Content.Add(project);
202    }
203
204    private async void removeButton_Click(object sender, EventArgs e) {
205      lock (locker) {
206        if (!removeButton.Enabled) return;
207        removeButton.Enabled = false;
208      }
209
210      var selectedNode = projectsTreeView.SelectedNode;
211      if (selectedNode == null || selectedNode.Tag == null) return;
212
213      var project = (Project)selectedNode.Tag;
214      var result = MessageBox.Show(
215        "Do you really want to delete " + project.Name + "?",
216        "HeuristicLab Hive Administrator",
217        MessageBoxButtons.YesNo,
218        MessageBoxIcon.Question);
219
220      if (result == DialogResult.Yes) {
221        if (Content.Any(x => x.ParentProjectId == project.Id)) {
222          MessageBox.Show(
223            "Only empty projects can be deleted.",
224            "HeuristicLab Hive Administrator",
225            MessageBoxButtons.OK,
226            MessageBoxIcon.Error);
227        } else {
228          await SecurityExceptionUtil.TryAsyncAndReportSecurityExceptions(
229            action: () => RemoveProject(project),
230            finallyCallback: () => {
231              Content.Remove(project);
232              removeButton.Enabled = true;
233            });
234        }
235      }
236    }
237
238    private async void saveProjectButton_Click(object sender, EventArgs e) {
239      lock (locker) {
240        if (!saveProjectButton.Enabled) return;
241        saveProjectButton.Enabled = false;
242      }
243
244      await SecurityExceptionUtil.TryAsyncAndReportSecurityExceptions(
245        action: () => {
246          var projectsToSave = Content.Where(x => x.Id == Guid.Empty || x.Modified);
247          foreach (var project in projectsToSave)
248            project.Store();
249        },
250        finallyCallback: () => saveProjectButton.Enabled = true);
251
252      OnContentChanged();
253    }
254
255    private void projectsTreeView_AfterSelect(object sender, TreeViewEventArgs e) {
256      selectedProject = (Project)e.Node.Tag;
257      ReColorTreeNodes(projectsTreeView.Nodes, selectedColor, Color.Transparent, true);
258      e.Node.BackColor = selectedColor;
259      e.Node.Text += " [selected]";
260     
261
262      //if (projectView.Content != null)
263      //  projectView.Content.PropertyChanged -= ProjectViewContent_PropertyChanged;
264
265      projectView.Content = selectedProject;
266      projectPermissionsView.Content = selectedProject;
267      projectResourcesView.Content = selectedProject;
268
269      //if (selectedProject != null)
270      //  selectedProject.PropertyChanged += ProjectViewContent_PropertyChanged;
271
272      //if (IsAuthorized(selectedProject)) {
273      //  if (!tabControl.TabPages.Contains(permissionsTabPage))
274      //    tabControl.TabPages.Add(permissionsTabPage);
275      //  if (!tabControl.TabPages.Contains(resourcesTabPage))
276      //    tabControl.TabPages.Add(resourcesTabPage);
277      //} else {
278      //  if (tabControl.TabPages.Contains(permissionsTabPage))
279      //    tabControl.TabPages.Remove(permissionsTabPage);
280      //  if (tabControl.TabPages.Contains(resourcesTabPage))
281      //    tabControl.TabPages.Remove(resourcesTabPage);
282      //}
283    }
284
285    private void projectsTreeView_DragDrop(object sender, DragEventArgs e) {
286      var sourceNode = (TreeNode)e.Data.GetData(typeof(TreeNode));
287      if (sourceNode == null) return;
288
289      var treeView = (TreeView)sender;
290      if (sourceNode.TreeView != treeView) return;
291
292      var targetPoint = treeView.PointToClient(new Point(e.X, e.Y));
293      var targetNode = treeView.GetNodeAt(targetPoint);
294
295      if (sourceNode == targetNode) return;
296
297      if (sourceNode.Parent == null)
298        treeView.Nodes.Remove(sourceNode);
299      else {
300        sourceNode.Parent.Nodes.Remove(sourceNode);
301        ((Project)sourceNode.Tag).ParentProjectId = null;
302      }
303
304      if (targetNode == null) {
305        treeView.Nodes.Add(sourceNode);
306      } else {
307        targetNode.Nodes.Add(sourceNode);
308        ((Project)sourceNode.Tag).ParentProjectId = ((Project)targetNode.Tag).Id;
309      }
310    }
311
312    private void projectsTreeView_ItemDrag(object sender, ItemDragEventArgs e) {
313      var sourceNode = (TreeNode)e.Item;
314      if (IsAuthorized((Project)sourceNode.Tag))
315        DoDragDrop(sourceNode, DragDropEffects.All);
316    }
317
318    private void projectsTreeView_DragEnter(object sender, DragEventArgs e) {
319      e.Effect = DragDropEffects.Move;
320    }
321
322    private void projectsTreeView_DragOver(object sender, DragEventArgs e) {
323      e.Effect = DragDropEffects.Move;
324    }
325
326    private void projectsTreeView_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) {
327      e.Action = DragAction.Continue;
328    }
329    #endregion
330
331    #region Helpers
332    private void ReColorTreeNodes(TreeNodeCollection nodes, Color c1, Color c2, bool resetText) {
333      foreach(TreeNode n in nodes) {
334        if(n.BackColor.Equals(c1)) {
335          n.BackColor = c2;
336          if (resetText) n.Text = ((Project)n.Tag).Name;
337        }
338        if (n.Nodes.Count > 0) {
339          ReColorTreeNodes(n.Nodes, c1, c2, resetText);
340        }
341      }
342    }
343
344    private Project BuildProjectTree(IEnumerable<Project> projects) {
345      projectsTreeView.Nodes.Clear();
346      if (!projects.Any()) return null;
347
348      var mainProjects = new HashSet<Project>(projects.Where(x => x.ParentProjectId == null));
349      var parentedMainProjects = new HashSet<Project>(projects
350        .Where(x => x.ParentProjectId.HasValue
351        && !projects.Select(y => y.Id).Contains(x.ParentProjectId.Value)));
352            mainProjects.UnionWith(parentedMainProjects);
353      var subProbjects = new HashSet<Project>(projects.Except(mainProjects));
354
355      var stack = new Stack<Project>(mainProjects.OrderByDescending(x => x.Name));
356      Project top = null;
357
358      TreeNode currentNode = null;
359      Project currentProject = null;
360     
361      while (stack.Any()) {
362        var newProject = stack.Pop();
363        var newNode = new TreeNode(newProject.Name) { Tag = newProject };
364        if (top == null) {
365          top = newProject;
366          newNode.BackColor = selectedColor;
367          newNode.Text += " [selected]";
368        }
369
370        while (currentNode != null && newProject.ParentProjectId != currentProject.Id) {
371          currentNode = currentNode.Parent;
372          currentProject = currentNode == null ? null : (Project)currentNode.Tag;
373        }
374
375        if (currentNode == null) {
376          projectsTreeView.Nodes.Add(newNode);
377          newNode.ImageIndex = greenFlagImageIndex;
378        } else {
379          currentNode.Nodes.Add(newNode);
380          newNode.ImageIndex = redFlagImageIndex;
381        }
382
383        newNode.SelectedImageIndex = newNode.ImageIndex;
384
385        var childProjects = subProbjects.Where(x => x.ParentProjectId == newProject.Id);
386        if (childProjects.Any()) {
387          foreach (var project in childProjects.OrderByDescending(x => x.Name)) {
388            subProbjects.Remove(project);
389            stack.Push(project);
390          }
391          currentNode = newNode;
392          currentProject = newProject;
393        }
394      }
395
396      projectsTreeView.ExpandAll();
397
398      return top;
399    }
400
401    private void UpdateProjects() {
402      try {
403        HiveAdminClient.Instance.Refresh();
404      } catch (AnonymousUserException) {
405        ShowHiveInformationDialog();
406      }
407    }
408
409    private void RemoveProject(Project project) {
410      try {
411        HiveAdminClient.Delete(project);
412      } catch (AnonymousUserException) {
413        ShowHiveInformationDialog();
414      }
415    }
416
417    private bool IsAuthorized(Project project) {
418      return project != null && UserInformation.Instance.UserExists;
419          //&& (project.OwnerUserId == UserInformation.Instance.User.Id || HiveRoles.CheckAdminUserPermissions());
420    }
421
422    private void ShowHiveInformationDialog() {
423      if (InvokeRequired) Invoke((Action)ShowHiveInformationDialog);
424      else {
425        using (HiveInformationDialog dialog = new HiveInformationDialog()) {
426          dialog.ShowDialog(this);
427        }
428      }
429    }
430    #endregion
431  }
432}
Note: See TracBrowser for help on using the repository browser.