source: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive.Server.Console/3.3/HiveServerManagementConsole.cs @ 4302

Last change on this file since 4302 was 4302, checked in by cneumuel, 12 years ago
  • made ServerConsole work with wsHttpBinding
  • applied role-base restrictions to all WCF-Services
  • made wcf-services work with certificates
  • renamed ExecutionEngineFacade to ClientFacade

(#1168)

File size: 31.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2008 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.Data;
26using System.Drawing;
27using System.Linq;
28using System.Text;
29using System.Windows.Forms;
30using HeuristicLab.Hive.Contracts.Interfaces;
31using HeuristicLab.Hive.Contracts.BusinessObjects;
32using HeuristicLab.Hive.Contracts;
33using System.Threading;
34using System.ServiceModel;
35using HeuristicLab.Tracing;
36using HeuristicLab.Hive.Contracts.ResponseObjects;
37
38namespace HeuristicLab.Hive.Server.ServerConsole {
39
40  /// <summary>
41  /// if form is closed the loginform gets an information
42  /// </summary>
43  /// <param name="cf"></param>
44  /// <param name="error"></param>
45  public delegate void closeForm(bool cf, bool error);
46
47  public delegate void updateListView(JobDataFetcher fetcher, ListView sender, int category);
48
49  public partial class HiveServerManagementConsole : Form {
50
51    public event closeForm closeFormEvent;
52
53    #region private variables
54    private ResponseList<JobDto> jobs = null;
55
56    List<ListViewGroup> jobGroup;
57    private Dictionary<Guid, List<ListViewItem>> clientList = new Dictionary<Guid, List<ListViewItem>>();
58    private List<Changes> changes = new List<Changes>();
59
60    private JobDto currentJob = null;
61    private SlaveDto currentSlave = null;
62
63    private TreeNode currentGroupNode = null;
64    Guid parentgroup = Guid.Empty;
65    private ToolTip tt = new ToolTip();
66
67    private const string NOGROUP = "No group";
68    private TreeNode hoverNode;
69    private List<ListViewGroup> lvSlaveGroups;
70
71    private JobDataFetcher jdfFinished = null;
72    private JobDataFetcher jdfOffline = null;
73    private JobDataFetcher jdfCalculating = null;
74
75
76    #endregion
77
78    #region Properties
79    private ISlaveManager SlaveManager {
80      get {
81        try {
82          return ServiceLocator.GetSlaveManager();
83        }
84        catch (FaultException ex) {
85          MessageBox.Show(ex.Message);
86        }
87        return null;
88      }
89    }
90    #endregion
91
92    public HiveServerManagementConsole() {
93      InitializeComponent();
94      Init();
95      AddSlaves();
96      //AddJobs();
97      StartAutoUpdateTimers();
98      //timerSyncronize.Start();
99    }
100
101    private void StartAutoUpdateTimers() {
102      jdfCalculating.NewDataAvailable += new EventHandler(jdf_NewDataAvailable);
103      jdfOffline.NewDataAvailable += new EventHandler(jdf_NewDataAvailable);
104      jdfFinished.NewDataAvailable += new EventHandler(jdf_NewDataAvailable);
105      jdfFinished.Start();
106      jdfOffline.Start();
107      jdfCalculating.Start();
108    }
109
110    void jdf_NewDataAvailable(object sender, EventArgs e) {
111      JobDataFetcher fetcher = (JobDataFetcher)sender;
112      if (fetcher.PollStates.Contains(JobState.Finished)) {
113        UpdateJobListView(fetcher, lv_finishedJobs, 0);
114      } else if (fetcher.PollStates.Contains(JobState.Calculating)) {
115        UpdateJobListView(fetcher, lv_calculatingJobs, 1);
116      } else if (fetcher.PollStates.Contains(JobState.Offline)) {
117        UpdateJobListView(fetcher, lv_offlineJobs, 2);
118      }
119    }
120
121    private void UpdateJobListView(JobDataFetcher fetcher, ListView listView, int category) {
122      if (listView.InvokeRequired) {
123        listView.Invoke(new updateListView(UpdateJobListView), new object[] { fetcher, listView, category });
124      } else {
125        listView.BeginUpdate();
126        listView.Items.Clear();
127        foreach (JobDto job in fetcher.CachedJobs) {
128          ListViewItem lvi = new ListViewItem(job.Id.ToString(), category);
129          lvi.Tag = job;
130          listView.Items.Add(lvi);
131        }
132        listView.EndUpdate();
133      }
134    }
135
136
137    private void Init() {
138
139      jdfFinished = new JobDataFetcher(new JobState[] { JobState.Finished }, 50);
140      jdfCalculating = new JobDataFetcher(new JobState[] { JobState.Calculating }, 50);
141      jdfOffline = new JobDataFetcher(new JobState[] { JobState.Offline }, 50);
142
143      cmb_finishedJob_count.SelectedItem = "50";
144      cmb_offlineJob_count.SelectedItem = "50";
145      cmb_calculatingJob_count.SelectedItem = "50";
146
147      calcToolStripAbortItem.Click += (s, e) => {
148        if (lv_calculatingJobs.SelectedItems.Count > 0) {
149          ServiceLocator.GetJobManager().AbortJob(((JobDto)lv_calculatingJobs.SelectedItems[0].Tag).Id);
150        }
151      };
152
153      offlineItemAbortJob.Click += (s, e) => {
154        if (lv_offlineJobs.SelectedItems.Count > 0) {
155          ServiceLocator.GetJobManager().AbortJob(((JobDto)lv_offlineJobs.SelectedItems[0].Tag).Id);
156        }
157      };
158
159      //adding group
160      menuItemAddGroup.Click += (s, e) => {
161        AddGroup addgroup = new AddGroup();
162        parentgroup = Guid.Empty;
163        if ((tvClientControl.SelectedNode != null) && (((SlaveGroupDto)tvClientControl.SelectedNode.Tag).Id != Guid.Empty)) {
164          parentgroup = ((SlaveGroupDto)tvClientControl.SelectedNode.Tag).Id;
165        }
166        addgroup.addGroupEvent += new AddGroupDelegate(addgroup_addGroupEvent);
167        addgroup.Show();
168      };
169
170      //adding group
171      menuItemDeleteGroup.Click += (s, e) => {
172        ISlaveManager slaveManager = ServiceLocator.GetSlaveManager();
173        if (tvClientControl.SelectedNode != null) {
174          Response resp = slaveManager.DeleteSlaveGroup(((SlaveGroupDto)tvClientControl.SelectedNode.Tag).Id);
175          if (tvClientControl.SelectedNode == currentGroupNode) {
176            currentGroupNode = null;
177          }
178          tvClientControl.Nodes.Remove(tvClientControl.SelectedNode);
179          AddSlaves();
180        }
181      };
182
183      menuItemOpenCalendar.Click += (s, e) => {
184        if (tvClientControl.SelectedNode != null) {
185          CgCalendar cal = new CgCalendar(((SlaveGroupDto)tvClientControl.SelectedNode.Tag).Id, ((SlaveGroupDto)tvClientControl.SelectedNode.Tag).Name);
186          cal.Show();
187        }
188      };
189
190
191      // drag item to treeview
192      lvClientControl.ItemDrag += delegate(object sender, ItemDragEventArgs e) {
193        List<string> itemIDs = new List<string>((sender as ListView).SelectedItems.Count);
194        foreach (ListViewItem item in (sender as ListView).SelectedItems) {
195          itemIDs.Add(item.Name);
196        }
197        (sender as ListView).DoDragDrop(itemIDs.ToArray(), DragDropEffects.Move);
198      };
199
200      // drag enter on treeview
201      tvClientControl.DragEnter += delegate(object sender, DragEventArgs e) {
202        e.Effect = DragDropEffects.Move;
203      };
204
205      // drag over
206      tvClientControl.DragOver += delegate(object sender, DragEventArgs e) {
207        Point mouseLocation = tvClientControl.PointToClient(new Point(e.X, e.Y));
208        TreeNode node = tvClientControl.GetNodeAt(mouseLocation);
209        if (node != null && ((SlaveGroupDto)node.Tag).Id != Guid.Empty) {
210          e.Effect = DragDropEffects.Move;
211          if (hoverNode == null) {
212            node.BackColor = Color.LightBlue;
213            node.ForeColor = Color.White;
214            hoverNode = node;
215          } else if (hoverNode != node) {
216            hoverNode.BackColor = Color.White;
217            hoverNode.ForeColor = Color.Black;
218            node.BackColor = Color.LightBlue;
219            node.ForeColor = Color.White;
220            hoverNode = node;
221          }
222        } else {
223          e.Effect = DragDropEffects.None;
224        }
225      };
226
227      // drag drop event
228      tvClientControl.DragDrop += delegate(object sender, DragEventArgs e) {
229        if (e.Data.GetDataPresent(typeof(string[]))) {
230          Point dropLocation = (sender as TreeView).PointToClient(new Point(e.X, e.Y));
231          TreeNode dropNode = (sender as TreeView).GetNodeAt(dropLocation);
232          if (((SlaveGroupDto)dropNode.Tag).Id != Guid.Empty) {
233            Dictionary<SlaveDto, Guid> clients = new Dictionary<SlaveDto, Guid>();
234            foreach (ListViewItem lvi in lvClientControl.SelectedItems) {
235              Guid groupId = Guid.Empty;
236              foreach (ListViewGroup lvg in lvSlaveGroups) {
237                if (lvi.Group.Header == ((SlaveGroupDto)lvg.Tag).Name) {
238                  groupId = ((SlaveGroupDto)lvg.Tag).Id;
239                }
240              }
241              clients.Add((SlaveDto)lvi.Tag, groupId);
242            }
243            ChangeGroup(clients, ((SlaveGroupDto)dropNode.Tag).Id);
244          }
245          tvClientControl_DragLeave(null, EventArgs.Empty);
246          AddSlaves();
247        }
248      };
249    }
250
251    /// <summary>
252    /// Change client to other group
253    /// </summary>
254    /// <param name="clients">list of clients</param>
255    /// <param name="clientgroupID">group of clients</param>
256    private void ChangeGroup(Dictionary<SlaveDto, Guid> clients, Guid clientgroupID) {
257      ISlaveManager slaveManager = ServiceLocator.GetSlaveManager();
258      foreach (KeyValuePair<SlaveDto, Guid> client in clients) {
259        if (client.Key.Id != Guid.Empty) {
260          Response resp = slaveManager.DeleteResourceFromGroup(client.Value, client.Key.Id);
261        }
262        slaveManager.AddResourceToGroup(clientgroupID, client.Key);
263      }
264    }
265
266    #region Backgroundworker
267    /// <summary>
268    /// event on Ticker
269    /// </summary>
270    /// <param name="obj"></param>
271    /// <param name="e"></param>
272    private void TickSync(object obj, EventArgs e) {
273      if (!updaterWoker.IsBusy) {
274        updaterWoker.RunWorkerAsync();
275      }
276    }
277
278    private void updaterWoker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
279      RefreshForm();
280    }
281
282    private void updaterWoker_DoWork(object sender, DoWorkEventArgs e) {
283      changes.Clear();
284
285      ResponseList<JobDto> jobsOld = jobs;
286      try {
287        IJobManager jobManager = ServiceLocator.GetJobManager();
288
289        jobs = jobManager.GetAllJobs();
290
291        IDictionary<int, JobDto> jobsOldHelp;
292        CloneList(jobsOld, out jobsOldHelp);
293
294        if (jobsOld != null && jobsOld.List != null && jobsOldHelp != null)
295          GetDelta(jobsOld.List, jobsOldHelp);
296
297      }
298      catch (FaultException fe) {
299        MessageBox.Show(fe.Message);
300      }
301
302    }
303
304    #endregion
305
306
307    private void AddSlaves() {
308      lvSlaveGroups = new List<ListViewGroup>();
309      clientList.Clear();
310      tvClientControl.Nodes.Clear();
311      try {
312        ResponseList<SlaveGroupDto> clientGroups = SlaveManager.GetAllSlaveGroups();
313
314        if (clientGroups != null && clientGroups.List != null) {
315          foreach (SlaveGroupDto cg in clientGroups.List) {
316            AddSlaveOrGroup(cg, null);
317          }
318
319          if (currentGroupNode != null) {
320            lvClientControl.Items.Clear();
321            lvClientControl.Groups.Clear();
322            AddGroupsToListView(currentGroupNode);
323          }
324          tvClientControl.ExpandAll();
325        }
326
327      }
328      catch (FaultException fe) {
329        MessageBox.Show(fe.Message);
330      }
331    }
332
333    private void AddSlaveOrGroup(SlaveGroupDto clientGroup, TreeNode currentNode) {
334      currentNode = CreateTreeNode(clientGroup, currentNode);
335      List<ListViewItem> clientGroupList = new List<ListViewItem>();
336      ListViewGroup lvg;
337      if (string.IsNullOrEmpty(clientGroup.Name)) {
338        lvg = new ListViewGroup(NOGROUP, HorizontalAlignment.Left);
339      } else {
340        lvg = new ListViewGroup(clientGroup.Name, HorizontalAlignment.Left);
341      }
342      lvClientControl.Groups.Add(lvg);
343      lvg.Tag = clientGroup;
344      lvSlaveGroups.Add(lvg);
345      foreach (ResourceDto resource in clientGroup.Resources) {
346        if (resource is SlaveDto) {
347          int percentageUsage = CapacityRam(((SlaveDto)resource).NrOfCores, ((SlaveDto)resource).NrOfFreeCores);
348          int usage = 3;
349          if ((((SlaveDto)resource).State != SlaveState.Offline) &&
350            (((SlaveDto)resource).State != SlaveState.NullState)) {
351            if ((percentageUsage >= 0) && (percentageUsage <= 25)) {
352              usage = 0;
353            } else if ((percentageUsage > 25) && (percentageUsage <= 75)) {
354              usage = 1;
355            } else if ((percentageUsage > 75) && (percentageUsage <= 100)) {
356              usage = 2;
357            }
358          }
359          ListViewItem lvi = new ListViewItem(resource.Name, usage, lvg);
360          lvi.Tag = resource as SlaveDto;
361          clientGroupList.Add(lvi);
362        } else if (resource is SlaveGroupDto) {
363          AddSlaveOrGroup(resource as SlaveGroupDto, currentNode);
364        }
365      }
366      clientList.Add(clientGroup.Id, clientGroupList);
367    }
368
369    private TreeNode CreateTreeNode(SlaveGroupDto clientGroup, TreeNode currentNode) {
370      TreeNode tn;
371      if (string.IsNullOrEmpty(clientGroup.Name)) {
372        tn = new TreeNode(NOGROUP);
373      } else {
374        tn = new TreeNode(clientGroup.Name);
375      }
376      tn.Tag = clientGroup;
377      if (currentNode == null) {
378        tvClientControl.Nodes.Add(tn);
379      } else {
380        currentNode.Nodes.Add(tn);
381      }
382      return tn;
383    }
384
385    private void AddGroupsToListView(TreeNode node) {
386      if (node != null) {
387        ListViewGroup lvg = new ListViewGroup(node.Text, HorizontalAlignment.Left);
388        lvClientControl.Groups.Add(lvg);
389        lvg.Tag = node.Tag;
390        foreach (ListViewItem item in clientList[((SlaveGroupDto)node.Tag).Id]) {
391          item.Group = lvg;
392          lvClientControl.Items.Add(item);
393        }
394
395        if (node.Nodes != null) {
396          foreach (TreeNode curNode in node.Nodes) {
397            AddGroupsToListView(curNode);
398          }
399        }
400      }
401    }
402
403    /// <summary>
404    /// if one job is clicked, the details for the clicked job are shown
405    /// in the second panel
406    /// </summary>
407    private void JobClicked() {
408      plJobDetails.Visible = true;
409      lvJobDetails.Items.Clear();
410
411      ResponseObject<JobDto> response = ServiceLocator.GetJobManager().GetJobByIdWithDetails(currentJob.Id);
412
413      if (response.StatusMessage != ResponseStatus.Ok || response.Obj == null)
414        return;
415
416      JobDto job = response.Obj;
417
418      //lvSnapshots.Enabled = true;
419
420      if (job.State == JobState.Offline) {
421        pbJobControl.Image = ilLargeImgJob.Images[2];
422      } else if (job.State == JobState.Calculating) {
423        pbJobControl.Image = ilLargeImgJob.Images[1];
424      } else if (job.State == JobState.Finished) {
425        pbJobControl.Image = ilLargeImgJob.Images[0];
426      }
427
428      lblJobName.Text = job.Id.ToString();
429      if (job.Percentage != null) {
430        progressJob.Value = (int)(currentJob.Percentage * 100);
431        lblProgress.Text = (int)(currentJob.Percentage * 100) + "% calculated";
432      }
433
434      ListViewItem lvi = new ListViewItem();
435      lvi.Text = "User:";
436      lvi.SubItems.Add(job.UserId.ToString());
437      lvJobDetails.Items.Add(lvi);
438
439      lvi = null;
440      lvi = new ListViewItem();
441      lvi.Text = "created at:";
442      lvi.SubItems.Add(job.DateCreated.ToString());
443      lvJobDetails.Items.Add(lvi);
444
445      if (job.ParentJob != null) {
446        lvi = null;
447        lvi = new ListViewItem();
448        lvi.Text = "Parent job:";
449        lvi.SubItems.Add(job.ParentJob.ToString());
450        lvJobDetails.Items.Add(lvi);
451      }
452
453      lvi = null;
454      lvi = new ListViewItem();
455      lvi.Text = "Priority:";
456      lvi.SubItems.Add(job.Priority.ToString());
457      lvJobDetails.Items.Add(lvi);
458
459      if (job.Project != null) {
460        lvi = null;
461        lvi = new ListViewItem();
462        lvi.Text = "Project:";
463        lvi.SubItems.Add(job.Project.Name.ToString());
464        lvJobDetails.Items.Add(lvi);
465      }
466
467      if (job.Slave != null) {
468        lvi = null;
469        lvi = new ListViewItem();
470        lvi.Text = "Calculation begin:";
471        lvi.SubItems.Add(job.DateCalculated.ToString());
472        lvJobDetails.Items.Add(lvi);
473
474
475        lvi = null;
476        lvi = new ListViewItem();
477        lvi.Text = "Slave calculated:";
478        lvi.SubItems.Add(job.Slave.Name.ToString());
479        lvJobDetails.Items.Add(lvi);
480
481        if (job.State == JobState.Finished) {
482          lvi = null;
483          lvi = new ListViewItem();
484          lvi.Text = "Calculation ended:";
485          lvi.SubItems.Add(job.DateFinished.ToString());
486          lvJobDetails.Items.Add(lvi);
487        }
488      }
489    }
490
491    /// <summary>
492    /// if one client is clicked, the details for the clicked client are shown
493    /// in the second panel
494    /// </summary>
495    private void SlaveClicked() {
496      plClientDetails.Visible = true;
497
498      if (currentSlave != null) {
499        int percentageUsage = CapacityRam(currentSlave.NrOfCores, currentSlave.NrOfFreeCores);
500        int usage = 3;
501        if ((currentSlave.State != SlaveState.Offline) && (currentSlave.State != SlaveState.NullState)) {
502          if ((percentageUsage >= 0) && (percentageUsage <= 25)) {
503            usage = 0;
504          } else if ((percentageUsage > 25) && (percentageUsage <= 75)) {
505            usage = 1;
506          } else if ((percentageUsage > 75) && (percentageUsage <= 100)) {
507            usage = 2;
508          }
509        }
510        pbClientControl.Image = ilLargeImgClient.Images[usage];
511        lblClientName.Text = currentSlave.Name;
512        lblLogin.Text = currentSlave.Login.ToString();
513        lblState.Text = currentSlave.State.ToString();
514      }
515    }
516
517    private void RefreshForm() {
518      foreach (Changes change in changes) {
519        if (change.Types == Type.Job) {
520          RefreshJob(change);
521        }
522      }
523    }
524
525    private void RefreshJob(Changes change) {
526      /*if (change.ChangeType == Change.Update) {
527        for (int i = 0; i < lvJobControl.Items.Count; i++) {
528          if (lvJobControl.Items[i].Text == change.ID.ToString()) {
529            foreach (JobDto job in jobs.List) {
530              if (job.Id == change.ID) {
531                lvJobControl.Items[i].Tag = job;
532                if (currentJob != null) {
533                  if (currentJob.Id == change.ID) {
534                    currentJob = job;
535                    JobClicked();
536                  }
537                }
538                break;
539              }
540            }
541            State state = jobs.List[change.Position].State;
542            if (state == State.finished) {
543              lvJobControl.Items[i].Group = jobGroup[1];
544              lvJobControl.Items[i].ImageIndex = 0;
545            } else if (state == State.calculating) {
546              lvJobControl.Items[i].Group = jobGroup[0];
547              lvJobControl.Items[i].ImageIndex = 1;
548            } else if (state == State.offline || state == State.pending) {
549              lvJobControl.Items[i].Group = jobGroup[2];
550              lvJobControl.Items[i].ImageIndex = 2;
551            }
552            lvJobControl.Refresh();
553          }
554        }
555      } else if (change.ChangeType == Change.Create) {
556
557        ListViewItem lvi = new ListViewItem(
558          change.ID.ToString(), 2, jobGroup[2]);
559        foreach (JobDto job in jobs.List) {
560          if (job.Id == change.ID) {
561            lvi.Tag = job;
562            break;
563          }
564        }
565        lvJobControl.Items.Add(lvi);
566
567      } else if (change.ChangeType == Change.Delete) {
568        for (int i = 0; i < lvJobControl.Items.Count; i++) {
569          if (change.ID.ToString() == lvJobControl.Items[i].Text.ToString()) {
570            lvJobControl.Items[i].Remove();
571            break;
572          }
573        }
574      }                    */
575    }
576
577
578    #region Eventhandlers
579    /// <summary>
580    /// Send event to Login-GUI when closing
581    /// </summary>
582    /// <param name="sender"></param>
583    /// <param name="e"></param>
584    private void Close_Click(object sender, EventArgs e) {
585      if (closeFormEvent != null) {
586        closeFormEvent(true, false);
587      }
588      this.Close();
589    }
590
591    /// <summary>
592    /// Send evnt to Login-GUI when closing
593    /// </summary>
594    /// <param name="sender"></param>
595    /// <param name="e"></param>
596    private void HiveServerConsoleInformation_FormClosing(object sender, FormClosingEventArgs e) {
597      if (closeFormEvent != null) {
598        closeFormEvent(true, false);
599      }
600    }
601
602    private void AddJob_Click(object sender, EventArgs e) {
603      AddJobForm newForm = new AddJobForm();
604      newForm.Show();
605      newForm.addJobEvent += new addDelegate(updaterWoker.RunWorkerAsync);
606    }
607
608    private void OnLVJobControlClicked(object sender, EventArgs e) {
609      JobListView jlv = (JobListView)sender;
610      currentJob = (JobDto)jlv.SelectedItems[0].Tag;
611      JobClicked();
612    }
613
614    private void lvJobControl_MouseMove(object sender, MouseEventArgs e) {
615      JobListView jlv = (JobListView)sender;
616      if ((jlv.GetItemAt(e.X, e.Y) != null) &&
617        (jlv.GetItemAt(e.X, e.Y).ToolTipText != null)) {
618        tt.SetToolTip(jlv, jlv.GetItemAt(e.X, e.Y).ToolTipText);
619      }
620    }
621
622    private void lvJobControl_MouseUp(object sender, MouseEventArgs e) {
623      // If the right mouse button was clicked and released,
624      // display the shortcut menu assigned to the ListView.
625      JobListView jlv = (JobListView)sender;
626      jlv.ContextMenuStrip.Items.Clear();
627      ListViewHitTestInfo hitTestInfo = jlv.HitTest(e.Location);
628      if (e.Button == MouseButtons.Right && hitTestInfo.Item != null && jlv.SelectedItems.Count == 1) {
629        JobDto selectedJob = (JobDto)jlv.SelectedItems[0].Tag;
630
631        if (selectedJob != null && selectedJob.State == JobState.Calculating) {
632          jlv.ContextMenuStrip.Items.Add(offlineItemAbortJob);
633          jlv.ContextMenuStrip.Items.Add(menuItemGetSnapshot);
634        }
635      }
636      jlv.ContextMenuStrip.Show(new Point(e.X, e.Y));
637    }
638
639    private void tvClientControl_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) {
640      lvClientControl.Items.Clear();
641      lvClientControl.Groups.Clear();
642      currentGroupNode = e.Node;
643      AddGroupsToListView(e.Node);
644    }
645
646    private void groupToolStripMenuItem_Click(object sender, EventArgs e) {
647      AddGroup addgroup = new AddGroup();
648      parentgroup = Guid.Empty;
649      if ((tvClientControl.SelectedNode != null) && (((SlaveGroupDto)tvClientControl.SelectedNode.Tag).Id != Guid.Empty)) {
650        parentgroup = ((SlaveGroupDto)tvClientControl.SelectedNode.Tag).Id;
651      }
652      addgroup.addGroupEvent += new AddGroupDelegate(addgroup_addGroupEvent);
653      addgroup.Show();
654    }
655
656    private void projectToolStripMenuItem_Click(object sender, EventArgs e) {
657      AddProject addproject = new AddProject();
658      addproject.AddProjectEvent += new AddProjectDelegate(addproject_AddProjectEvent);
659      addproject.Show();
660    }
661
662    private void OnLVClientClicked(object sender, EventArgs e) {
663      currentSlave = (SlaveDto)lvClientControl.SelectedItems[0].Tag;
664      SlaveClicked();
665    }
666
667    private void tvClientControl_MouseUp(object sender, MouseEventArgs e) {
668      // If the right mouse button was clicked and released,
669      // display the shortcut menu assigned to the ListView.
670      contextMenuGroup.Items.Clear();
671      TreeViewHitTestInfo hitTestInfo = tvClientControl.HitTest(e.Location);
672      tvClientControl.SelectedNode = hitTestInfo.Node;
673      if (e.Button != MouseButtons.Right) return;
674      if (hitTestInfo.Node != null) {
675        ResourceDto selectedGroup = (ResourceDto)tvClientControl.SelectedNode.Tag;
676
677        if (selectedGroup != null) {
678          contextMenuGroup.Items.Add(menuItemAddGroup);
679          contextMenuGroup.Items.Add(menuItemDeleteGroup);
680          contextMenuGroup.Items.Add(menuItemOpenCalendar);
681        }
682      } else {
683        contextMenuGroup.Items.Add(menuItemAddGroup);
684      }
685      tvClientControl.ContextMenuStrip.Show(tvClientControl, new Point(e.X, e.Y));
686    }
687
688    private void addproject_AddProjectEvent(string name) {
689      IJobManager jobManager = ServiceLocator.GetJobManager();
690
691      ProjectDto pg = new ProjectDto() { Name = name };
692      jobManager.CreateProject(pg);
693
694    }
695
696    private void addgroup_addGroupEvent(string name) {
697      ISlaveManager slaveManager = ServiceLocator.GetSlaveManager();
698
699      if (parentgroup != Guid.Empty) {
700        SlaveGroupDto cg = new SlaveGroupDto() { Name = name };
701        ResponseObject<SlaveGroupDto> respcg = slaveManager.AddSlaveGroup(cg);
702        Response res = slaveManager.AddResourceToGroup(parentgroup, respcg.Obj);
703        if (res != null && res.StatusMessage != ResponseStatus.Ok) {
704          MessageBox.Show(res.StatusMessage.ToString(), "Error adding Group", MessageBoxButtons.OK, MessageBoxIcon.Error);
705        }
706      } else {
707        SlaveGroupDto cg = new SlaveGroupDto() { Name = name };
708        slaveManager.AddSlaveGroup(cg);
709      }
710      AddSlaves();
711    }
712
713
714    private void Refresh_Click(object sender, EventArgs e) {
715      Form overlayingForm = new Form();
716
717      overlayingForm.Show();
718      overlayingForm.FormBorderStyle = FormBorderStyle.None;
719      overlayingForm.BackColor = Color.Gray;
720      overlayingForm.Opacity = 0.4;
721      overlayingForm.Size = this.Size;
722      overlayingForm.Location = this.Location;
723
724      AddSlaves();
725
726      overlayingForm.Close();
727    }
728
729    private void largeIconsToolStripMenuItem_Click(object sender, EventArgs e) {
730      lvClientControl.View = View.LargeIcon;
731      //lvJobControl.View = View.LargeIcon;
732      largeIconsToolStripMenuItem.CheckState = CheckState.Checked;
733      smallIconsToolStripMenuItem.CheckState = CheckState.Unchecked;
734      listToolStripMenuItem.CheckState = CheckState.Unchecked;
735    }
736
737    private void smallIconsToolStripMenuItem_Click(object sender, EventArgs e) {
738      lvClientControl.View = View.SmallIcon;
739      //lvJobControl.View = View.SmallIcon;
740      largeIconsToolStripMenuItem.CheckState = CheckState.Unchecked;
741      smallIconsToolStripMenuItem.CheckState = CheckState.Checked;
742      listToolStripMenuItem.CheckState = CheckState.Unchecked;
743    }
744
745    private void listToolStripMenuItem_Click(object sender, EventArgs e) {
746      lvClientControl.View = View.List;
747      //lvJobControl.View = View.List;
748      largeIconsToolStripMenuItem.CheckState = CheckState.Unchecked;
749      smallIconsToolStripMenuItem.CheckState = CheckState.Unchecked;
750      listToolStripMenuItem.CheckState = CheckState.Checked;
751    }
752
753    private void tvClientControl_DragLeave(object sender, EventArgs e) {
754      foreach (TreeNode node in tvClientControl.Nodes) {
755        node.BackColor = Color.White;
756        node.ForeColor = Color.Black;
757      }
758    }
759    #endregion
760
761    #region Helper methods
762
763    private void CloneList(ResponseList<JobDto> oldList, out IDictionary<int, JobDto> newList) {
764      newList = new Dictionary<int, JobDto>();
765      if (oldList != null && oldList.List != null) {
766        for (int i = 0; i < oldList.List.Count; i++) {
767          newList.Add(i, oldList.List[i]);
768        }
769      }
770    }
771
772    private bool IsEqual(SlaveDto ci1, SlaveDto ci2) {
773      if (ci1 == null && ci2 == null) {
774        return true;
775      }
776      if (ci2 == null) {
777        return false;
778      }
779      if (ci1.Id.Equals(ci2.Id)) {
780        return true;
781      } else return false;
782    }
783
784    private int CapacityRam(int noCores, int freeCores) {
785      if (noCores > 0) {
786        int capacity = ((noCores - freeCores) / noCores) * 100;
787        return capacity;
788      }
789      return 100;
790    }
791
792    private void GetDelta(IList<JobDto> oldJobs, IDictionary<int, JobDto> helpJobs) {
793      bool found = false;
794      for (int i = 0; i < jobs.List.Count; i++) {
795        JobDto job = jobs.List[i];
796        for (int j = 0; j < oldJobs.Count; j++) {
797
798          JobDto jobold = oldJobs[j];
799
800          if (job.Id.Equals(jobold.Id)) {
801
802            found = true;
803            bool change = false;
804            if (job.State != jobold.State) {
805              change = true;
806            }
807            if (job.State != JobState.Offline) {
808              if ((!IsEqual(job.Slave, jobold.Slave)) || (job.State != jobold.State)
809                   || (job.Percentage != jobold.Percentage)) {
810                change = true;
811              }
812            } else if (job.DateCalculated != jobold.DateCalculated) {
813              change = true;
814            }
815            if (change) {
816              changes.Add(new Changes { Types = Type.Job, ID = job.Id, ChangeType = Change.Update, Position = i });
817            }
818
819            int removeAt = -1;
820            foreach (KeyValuePair<int, JobDto> kvp in helpJobs) {
821              if (job.Id.Equals(kvp.Value.Id)) {
822                removeAt = kvp.Key;
823                break;
824              }
825            }
826            if (removeAt >= 0) {
827              helpJobs.Remove(removeAt);
828            }
829            break;
830          }
831
832        }
833        if (found == false) {
834          changes.Add(new Changes { Types = Type.Job, ID = job.Id, ChangeType = Change.Create });
835        }
836        found = false;
837      }
838      foreach (KeyValuePair<int, JobDto> kvp in helpJobs) {
839        changes.Add(new Changes { Types = Type.Job, ID = kvp.Value.Id, ChangeType = Change.Delete, Position = kvp.Key });
840      }
841    }
842
843    #endregion
844
845    private void btn_prev_Click(object sender, EventArgs e) {
846      if (sender == btn_finishedJob_prev)
847        jdfFinished.Backward();
848      else if (sender == btn_calculatingJobs_prev)
849        jdfCalculating.Backward();
850      else if (sender == btn_offlinejob_prev) {
851        jdfOffline.Backward();
852      }
853    }
854
855    private void btn_next_Click(object sender, EventArgs e) {
856      if (sender == btn_finishedJob_next)
857        jdfFinished.Forward();
858      else if (sender == btn_calculatingJobs_next)
859        jdfCalculating.Forward();
860      else if (sender == btn_offlineJob_next) {
861        jdfOffline.Forward();
862      }
863    }
864
865    private void cmb_count_SelectedIndexChanged(object sender, EventArgs e) {
866      ComboBox box = (ComboBox)sender;
867      if (box.SelectedItem != null) {
868        int val;
869        if (Int32.TryParse(box.SelectedItem.ToString(), out val)) {
870          if (box == cmb_offlineJob_count) {
871            jdfOffline.NrOfEntriesOnPage = val;
872          } else if (box == cmb_finishedJob_count) {
873            jdfFinished.NrOfEntriesOnPage = val;
874          } else if (box == cmb_calculatingJob_count) {
875            jdfCalculating.NrOfEntriesOnPage = val;
876          }
877        }
878      }
879    }
880
881    private void lv_Jobs_SelectedIndexChanged(object sender, EventArgs e) {
882      ListView lv = (ListView)sender;
883      if (lv.SelectedItems.Count > 0) {
884        foreach (ListViewItem lvi in lv.SelectedItems) {
885          currentJob = (JobDto)lvi.Tag;
886          JobClicked();
887        }
888      }
889    }
890  }
891}
Note: See TracBrowser for help on using the repository browser.