Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 4263 was 4263, checked in by cneumuel, 12 years ago

consolidated Response objects to use only StatusMessage with enums instead of strings.
removed Success property from Response. success is now represented by StatusMessage alone. (#1159)

File size: 31.4 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 ClientDto currentClient = 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> lvClientGroups;
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 ClientManager {
80      get {
81        try {
82          return ServiceLocator.GetClientManager();
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      AddClients();
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(State.Finished)) {
113        updateJobListView(fetcher, lv_finishedJobs, 0);
114      } else if(fetcher.PollStates.Contains(State.Calculating)) {
115        updateJobListView(fetcher, lv_calculatingJobs, 1);
116      } else if (fetcher.PollStates.Contains(State.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 State[] {State.Finished}, 50);
140      jdfCalculating = new JobDataFetcher(new State[] {State.Calculating}, 50);
141      jdfOffline = new JobDataFetcher(new State[] {State.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) && (((ClientGroupDto)tvClientControl.SelectedNode.Tag).Id != Guid.Empty)) {
164          parentgroup = ((ClientGroupDto)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 clientManager = ServiceLocator.GetClientManager();
173        if (tvClientControl.SelectedNode != null) {
174          Response resp = clientManager.DeleteClientGroup(((ClientGroupDto)tvClientControl.SelectedNode.Tag).Id);
175          if (tvClientControl.SelectedNode == currentGroupNode) {
176            currentGroupNode = null;
177          }
178          tvClientControl.Nodes.Remove(tvClientControl.SelectedNode);
179          AddClients();
180        }
181      };
182
183      menuItemOpenCalendar.Click += (s, e) => {
184                                      if (tvClientControl.SelectedNode != null) {
185                                        CgCalendar cal = new CgCalendar(((ClientGroupDto)tvClientControl.SelectedNode.Tag).Id, ((ClientGroupDto)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 && ((ClientGroupDto)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 (((ClientGroupDto)dropNode.Tag).Id != Guid.Empty) {
233            Dictionary<ClientDto, Guid> clients = new Dictionary<ClientDto, Guid>();
234            foreach (ListViewItem lvi in lvClientControl.SelectedItems) {
235              Guid groupId = Guid.Empty;
236              foreach (ListViewGroup lvg in lvClientGroups) {
237                if (lvi.Group.Header == ((ClientGroupDto)lvg.Tag).Name) {
238                  groupId = ((ClientGroupDto)lvg.Tag).Id;
239                }
240              }
241              clients.Add((ClientDto)lvi.Tag, groupId);
242            }
243            ChangeGroup(clients, ((ClientGroupDto)dropNode.Tag).Id);
244          }
245          tvClientControl_DragLeave(null, EventArgs.Empty);
246          AddClients();
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<ClientDto, Guid> clients, Guid clientgroupID) {
257      ISlaveManager clientManager = ServiceLocator.GetClientManager();
258      foreach (KeyValuePair<ClientDto, Guid> client in clients) {
259        if (client.Key.Id != Guid.Empty) {
260          Response resp = clientManager.DeleteResourceFromGroup(client.Value, client.Key.Id);
261        }
262        clientManager.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 =
288                ServiceLocator.GetJobManager();
289
290        jobs = jobManager.GetAllJobs();
291
292        IDictionary<int, JobDto> jobsOldHelp;
293        CloneList(jobsOld, out jobsOldHelp);
294
295        if(jobsOld != null && jobsOld.List != null && jobsOldHelp != null)
296          GetDelta(jobsOld.List, jobsOldHelp);
297
298      }
299      catch (FaultException fe) {
300        MessageBox.Show(fe.Message);
301      }
302
303    }
304
305    #endregion
306
307
308    private void AddClients() {
309      lvClientGroups = new List<ListViewGroup>();
310      clientList.Clear();
311      tvClientControl.Nodes.Clear();
312      try {
313        ResponseList<ClientGroupDto> clientGroups = ClientManager.GetAllClientGroups();
314
315        if (clientGroups != null && clientGroups.List != null) {
316          foreach (ClientGroupDto cg in clientGroups.List) {
317            AddClientOrGroup(cg, null);
318          }
319
320          if (currentGroupNode != null) {
321            lvClientControl.Items.Clear();
322            lvClientControl.Groups.Clear();
323            AddGroupsToListView(currentGroupNode);
324          }
325          tvClientControl.ExpandAll();
326        }
327
328      }
329      catch (FaultException fe) {
330        MessageBox.Show(fe.Message);
331      }
332    }
333
334    private void AddClientOrGroup(ClientGroupDto clientGroup, TreeNode currentNode) {
335      currentNode = CreateTreeNode(clientGroup, currentNode);
336      List<ListViewItem> clientGroupList = new List<ListViewItem>();
337      ListViewGroup lvg;
338      if (string.IsNullOrEmpty(clientGroup.Name)) {
339        lvg = new ListViewGroup(NOGROUP, HorizontalAlignment.Left);
340      } else {
341        lvg = new ListViewGroup(clientGroup.Name, HorizontalAlignment.Left);
342      }
343      lvClientControl.Groups.Add(lvg);
344      lvg.Tag = clientGroup;
345      lvClientGroups.Add(lvg);
346      foreach (ResourceDto resource in clientGroup.Resources) {
347        if (resource is ClientDto) {
348          int percentageUsage = CapacityRam(((ClientDto)resource).NrOfCores, ((ClientDto)resource).NrOfFreeCores);
349          int usage = 3;
350          if ((((ClientDto)resource).State != State.Offline) &&
351            (((ClientDto)resource).State != State.NullState)) {
352            if ((percentageUsage >= 0) && (percentageUsage <= 25)) {
353              usage = 0;
354            } else if ((percentageUsage > 25) && (percentageUsage <= 75)) {
355              usage = 1;
356            } else if ((percentageUsage > 75) && (percentageUsage <= 100)) {
357              usage = 2;
358            }
359          }
360          ListViewItem lvi = new ListViewItem(resource.Name, usage, lvg);
361          lvi.Tag = resource as ClientDto;
362          clientGroupList.Add(lvi);
363        } else if (resource is ClientGroupDto) {
364          AddClientOrGroup(resource as ClientGroupDto, currentNode);
365        }
366      }
367      clientList.Add(clientGroup.Id, clientGroupList);
368    }
369
370    private TreeNode CreateTreeNode(ClientGroupDto clientGroup, TreeNode currentNode) {
371      TreeNode tn;
372      if (string.IsNullOrEmpty(clientGroup.Name)) {
373        tn = new TreeNode(NOGROUP);
374      } else {
375        tn = new TreeNode(clientGroup.Name);
376      }
377      tn.Tag = clientGroup;
378      if (currentNode == null) {
379        tvClientControl.Nodes.Add(tn);
380      } else {
381        currentNode.Nodes.Add(tn);
382      }
383      return tn;
384    }
385
386    private void AddGroupsToListView(TreeNode node) {
387      if (node != null) {
388        ListViewGroup lvg = new ListViewGroup(node.Text, HorizontalAlignment.Left);
389        lvClientControl.Groups.Add(lvg);
390        lvg.Tag = node.Tag;
391        foreach (ListViewItem item in clientList[((ClientGroupDto)node.Tag).Id]) {
392          item.Group = lvg;
393          lvClientControl.Items.Add(item);
394        }
395
396        if (node.Nodes != null) {
397          foreach (TreeNode curNode in node.Nodes) {
398            AddGroupsToListView(curNode);
399          }
400        }
401      }
402    }
403
404    /// <summary>
405    /// if one job is clicked, the details for the clicked job are shown
406    /// in the second panel
407    /// </summary>
408    private void JobClicked() {
409      plJobDetails.Visible = true;
410      lvJobDetails.Items.Clear();
411
412      ResponseObject<JobDto> response = ServiceLocator.GetJobManager().GetJobByIdWithDetails(currentJob.Id);
413
414      if(response.StatusMessage != ResponseStatus.Ok || response.Obj == null)
415        return;
416
417      JobDto job = response.Obj;
418
419      //lvSnapshots.Enabled = true;
420
421      if (job.State == State.Offline) {
422        pbJobControl.Image = ilLargeImgJob.Images[2];
423      } else if (job.State == State.Calculating) {
424        pbJobControl.Image = ilLargeImgJob.Images[1];
425      } else if (job.State == State.Finished) {
426        pbJobControl.Image = ilLargeImgJob.Images[0];
427      }
428
429      lblJobName.Text = job.Id.ToString();
430      if (job.Percentage != null) {
431        progressJob.Value = (int) (currentJob.Percentage*100);
432        lblProgress.Text = (int) (currentJob.Percentage*100) + "% calculated";
433      }
434
435      ListViewItem lvi = new ListViewItem();
436      lvi.Text = "User:";
437      lvi.SubItems.Add(job.UserId.ToString());
438      lvJobDetails.Items.Add(lvi);
439
440      lvi = null;
441      lvi = new ListViewItem();
442      lvi.Text = "created at:";
443      lvi.SubItems.Add(job.DateCreated.ToString());
444      lvJobDetails.Items.Add(lvi);
445
446      if (job.ParentJob != null) {
447        lvi = null;
448        lvi = new ListViewItem();
449        lvi.Text = "Parent job:";
450        lvi.SubItems.Add(job.ParentJob.ToString());
451        lvJobDetails.Items.Add(lvi);
452      }
453
454      lvi = null;
455      lvi = new ListViewItem();
456      lvi.Text = "Priority:";
457      lvi.SubItems.Add(job.Priority.ToString());
458      lvJobDetails.Items.Add(lvi);
459
460      if (job.Project != null) {
461        lvi = null;
462        lvi = new ListViewItem();
463        lvi.Text = "Project:";
464        lvi.SubItems.Add(job.Project.Name.ToString());
465        lvJobDetails.Items.Add(lvi);
466      }
467
468      if (job.Client != null) {
469        lvi = null;
470        lvi = new ListViewItem();
471        lvi.Text = "Calculation begin:";
472        lvi.SubItems.Add(job.DateCalculated.ToString());
473        lvJobDetails.Items.Add(lvi);
474
475
476        lvi = null;
477        lvi = new ListViewItem();
478        lvi.Text = "Client calculated:";
479        lvi.SubItems.Add(job.Client.Name.ToString());
480        lvJobDetails.Items.Add(lvi);
481
482        if (job.State == State.Finished) {
483          lvi = null;
484            lvi = new ListViewItem();
485            lvi.Text = "Calculation ended:";
486            lvi.SubItems.Add(job.DateFinished.ToString());
487            lvJobDetails.Items.Add(lvi);
488          }
489        }
490      }
491
492    /// <summary>
493    /// if one client is clicked, the details for the clicked client are shown
494    /// in the second panel
495    /// </summary>
496    private void ClientClicked() {
497      plClientDetails.Visible = true;
498
499      if (currentClient != null) {
500        int percentageUsage = CapacityRam(currentClient.NrOfCores, currentClient.NrOfFreeCores);
501        int usage = 3;
502        if ((currentClient.State != State.Offline) && (currentClient.State != State.NullState)) {
503          if ((percentageUsage >= 0) && (percentageUsage <= 25)) {
504            usage = 0;
505          } else if ((percentageUsage > 25) && (percentageUsage <= 75)) {
506            usage = 1;
507          } else if ((percentageUsage > 75) && (percentageUsage <= 100)) {
508            usage = 2;
509          }
510        }
511        pbClientControl.Image = ilLargeImgClient.Images[usage];
512        lblClientName.Text = currentClient.Name;
513        lblLogin.Text = currentClient.Login.ToString();
514        lblState.Text = currentClient.State.ToString();
515      }
516    }
517
518    private void RefreshForm() {
519      foreach (Changes change in changes) {
520        if (change.Types == Type.Job) {
521          RefreshJob(change);
522        }
523      }
524    }
525
526    private void RefreshJob(Changes change) {
527      /*if (change.ChangeType == Change.Update) {
528        for (int i = 0; i < lvJobControl.Items.Count; i++) {
529          if (lvJobControl.Items[i].Text == change.ID.ToString()) {
530            foreach (JobDto job in jobs.List) {
531              if (job.Id == change.ID) {
532                lvJobControl.Items[i].Tag = job;
533                if (currentJob != null) {
534                  if (currentJob.Id == change.ID) {
535                    currentJob = job;
536                    JobClicked();
537                  }
538                }
539                break;
540              }
541            }
542            State state = jobs.List[change.Position].State;
543            if (state == State.finished) {
544              lvJobControl.Items[i].Group = jobGroup[1];
545              lvJobControl.Items[i].ImageIndex = 0;
546            } else if (state == State.calculating) {
547              lvJobControl.Items[i].Group = jobGroup[0];
548              lvJobControl.Items[i].ImageIndex = 1;
549            } else if (state == State.offline || state == State.pending) {
550              lvJobControl.Items[i].Group = jobGroup[2];
551              lvJobControl.Items[i].ImageIndex = 2;
552            }
553            lvJobControl.Refresh();
554          }
555        }
556      } else if (change.ChangeType == Change.Create) {
557
558        ListViewItem lvi = new ListViewItem(
559          change.ID.ToString(), 2, jobGroup[2]);
560        foreach (JobDto job in jobs.List) {
561          if (job.Id == change.ID) {
562            lvi.Tag = job;
563            break;
564          }
565        }
566        lvJobControl.Items.Add(lvi);
567
568      } else if (change.ChangeType == Change.Delete) {
569        for (int i = 0; i < lvJobControl.Items.Count; i++) {
570          if (change.ID.ToString() == lvJobControl.Items[i].Text.ToString()) {
571            lvJobControl.Items[i].Remove();
572            break;
573          }
574        }
575      }                    */
576    }
577
578
579    #region Eventhandlers
580    /// <summary>
581    /// Send event to Login-GUI when closing
582    /// </summary>
583    /// <param name="sender"></param>
584    /// <param name="e"></param>
585    private void Close_Click(object sender, EventArgs e) {
586      if (closeFormEvent != null) {
587        closeFormEvent(true, false);
588      }
589      this.Close();
590    }
591
592    /// <summary>
593    /// Send evnt to Login-GUI when closing
594    /// </summary>
595    /// <param name="sender"></param>
596    /// <param name="e"></param>
597    private void HiveServerConsoleInformation_FormClosing(object sender, FormClosingEventArgs e) {
598      if (closeFormEvent != null) {
599        closeFormEvent(true, false);
600      }
601    }
602
603    private void AddJob_Click(object sender, EventArgs e) {
604      AddJobForm newForm = new AddJobForm();
605      newForm.Show();
606      newForm.addJobEvent += new addDelegate(updaterWoker.RunWorkerAsync);
607    }
608
609    private void OnLVJobControlClicked(object sender, EventArgs e) {
610      JobListView jlv = (JobListView) sender;
611      currentJob = (JobDto)jlv.SelectedItems[0].Tag;
612      JobClicked();
613    }
614
615    private void lvJobControl_MouseMove(object sender, MouseEventArgs e) {
616      JobListView jlv = (JobListView) sender;
617      if ((jlv.GetItemAt(e.X, e.Y) != null) &&
618        (jlv.GetItemAt(e.X, e.Y).ToolTipText != null)) {
619        tt.SetToolTip(jlv, jlv.GetItemAt(e.X, e.Y).ToolTipText);
620      }
621    }
622
623    private void lvJobControl_MouseUp(object sender, MouseEventArgs e) {
624      // If the right mouse button was clicked and released,
625      // display the shortcut menu assigned to the ListView.
626      JobListView jlv = (JobListView)sender;
627      jlv.ContextMenuStrip.Items.Clear();
628      ListViewHitTestInfo hitTestInfo = jlv.HitTest(e.Location);
629      if (e.Button == MouseButtons.Right && hitTestInfo.Item != null && jlv.SelectedItems.Count == 1) {
630        JobDto selectedJob = (JobDto)jlv.SelectedItems[0].Tag;
631
632        if (selectedJob != null && selectedJob.State == State.Calculating) {
633          jlv.ContextMenuStrip.Items.Add(offlineItemAbortJob);
634          jlv.ContextMenuStrip.Items.Add(menuItemGetSnapshot);
635        }
636      }
637      jlv.ContextMenuStrip.Show(new Point(e.X, e.Y));
638    }
639
640    private void tvClientControl_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) {
641      lvClientControl.Items.Clear();
642      lvClientControl.Groups.Clear();
643      currentGroupNode = e.Node;
644      AddGroupsToListView(e.Node);
645    }
646
647    private void groupToolStripMenuItem_Click(object sender, EventArgs e) {
648      AddGroup addgroup = new AddGroup();
649      parentgroup = Guid.Empty;
650      if ((tvClientControl.SelectedNode != null) && (((ClientGroupDto)tvClientControl.SelectedNode.Tag).Id != Guid.Empty)) {
651        parentgroup = ((ClientGroupDto)tvClientControl.SelectedNode.Tag).Id;
652      }
653      addgroup.addGroupEvent += new AddGroupDelegate(addgroup_addGroupEvent);
654      addgroup.Show();
655    }
656
657    private void projectToolStripMenuItem_Click(object sender, EventArgs e) {
658      AddProject addproject = new AddProject();
659      addproject.AddProjectEvent += new AddProjectDelegate(addproject_AddProjectEvent);
660      addproject.Show();
661    }
662
663    private void OnLVClientClicked(object sender, EventArgs e) {
664      currentClient = (ClientDto)lvClientControl.SelectedItems[0].Tag;
665      ClientClicked();
666    }
667
668    private void tvClientControl_MouseUp(object sender, MouseEventArgs e) {
669      // If the right mouse button was clicked and released,
670      // display the shortcut menu assigned to the ListView.
671      contextMenuGroup.Items.Clear();
672      TreeViewHitTestInfo hitTestInfo = tvClientControl.HitTest(e.Location);
673      tvClientControl.SelectedNode = hitTestInfo.Node;
674      if (e.Button != MouseButtons.Right) return;
675      if (hitTestInfo.Node != null) {
676        ResourceDto selectedGroup = (ResourceDto)tvClientControl.SelectedNode.Tag;
677
678        if (selectedGroup != null) {
679          contextMenuGroup.Items.Add(menuItemAddGroup);
680          contextMenuGroup.Items.Add(menuItemDeleteGroup);
681          contextMenuGroup.Items.Add(menuItemOpenCalendar);
682        }
683      } else {
684        contextMenuGroup.Items.Add(menuItemAddGroup);
685      }
686      tvClientControl.ContextMenuStrip.Show(tvClientControl, new Point(e.X, e.Y));
687    }
688
689    private void addproject_AddProjectEvent(string name) {
690      IJobManager jobManager = ServiceLocator.GetJobManager();
691
692      ProjectDto pg = new ProjectDto() { Name = name };
693      jobManager.CreateProject(pg);
694
695    }
696
697    private void addgroup_addGroupEvent(string name) {
698      ISlaveManager clientManager = ServiceLocator.GetClientManager();
699
700      if (parentgroup != Guid.Empty) {
701        ClientGroupDto cg = new ClientGroupDto() { Name = name };
702        ResponseObject<ClientGroupDto> respcg = clientManager.AddClientGroup(cg);
703        Response res = clientManager.AddResourceToGroup(parentgroup, respcg.Obj);
704        if (res != null && res.StatusMessage != ResponseStatus.Ok) {
705          MessageBox.Show(res.StatusMessage.ToString(), "Error adding Group", MessageBoxButtons.OK, MessageBoxIcon.Error);
706        }
707      } else {
708        ClientGroupDto cg = new ClientGroupDto() { Name = name };
709        clientManager.AddClientGroup(cg);
710      }
711      AddClients();
712    }
713
714
715    private void Refresh_Click(object sender, EventArgs e) {
716      Form overlayingForm = new Form();
717
718      overlayingForm.Show();
719      overlayingForm.FormBorderStyle = FormBorderStyle.None;
720      overlayingForm.BackColor = Color.Gray;
721      overlayingForm.Opacity = 0.4;
722      overlayingForm.Size = this.Size;
723      overlayingForm.Location = this.Location;
724
725      AddClients();
726
727      overlayingForm.Close();
728    }
729
730    private void largeIconsToolStripMenuItem_Click(object sender, EventArgs e) {
731      lvClientControl.View = View.LargeIcon;
732      //lvJobControl.View = View.LargeIcon;
733      largeIconsToolStripMenuItem.CheckState = CheckState.Checked;
734      smallIconsToolStripMenuItem.CheckState = CheckState.Unchecked;
735      listToolStripMenuItem.CheckState = CheckState.Unchecked;
736    }
737
738    private void smallIconsToolStripMenuItem_Click(object sender, EventArgs e) {
739      lvClientControl.View = View.SmallIcon;
740      //lvJobControl.View = View.SmallIcon;
741      largeIconsToolStripMenuItem.CheckState = CheckState.Unchecked;
742      smallIconsToolStripMenuItem.CheckState = CheckState.Checked;
743      listToolStripMenuItem.CheckState = CheckState.Unchecked;
744    }
745
746    private void listToolStripMenuItem_Click(object sender, EventArgs e) {
747      lvClientControl.View = View.List;
748      //lvJobControl.View = View.List;
749      largeIconsToolStripMenuItem.CheckState = CheckState.Unchecked;
750      smallIconsToolStripMenuItem.CheckState = CheckState.Unchecked;
751      listToolStripMenuItem.CheckState = CheckState.Checked;
752    }
753
754    private void tvClientControl_DragLeave(object sender, EventArgs e) {
755      foreach (TreeNode node in tvClientControl.Nodes) {
756        node.BackColor = Color.White;
757        node.ForeColor = Color.Black;
758      }
759    }
760    #endregion
761
762    #region Helper methods
763
764    private void CloneList(ResponseList<JobDto> oldList, out IDictionary<int, JobDto> newList) {
765      newList = new Dictionary<int, JobDto>();
766      if (oldList != null && oldList.List != null) {
767        for (int i = 0; i < oldList.List.Count; i++) {
768          newList.Add(i, oldList.List[i]);
769        }
770      }
771    }
772
773    private bool IsEqual(ClientDto ci1, ClientDto ci2) {
774      if (ci1 == null && ci2 == null) {
775        return true;
776      }
777      if (ci2 == null) {
778        return false;
779      }
780      if (ci1.Id.Equals(ci2.Id)) {
781        return true;
782      } else return false;
783    }
784
785    private int CapacityRam(int noCores, int freeCores) {   
786      if (noCores > 0) {
787        int capacity = ((noCores - freeCores) / noCores) * 100;
788        return capacity;
789      }
790      return 100;
791    }
792
793    private void GetDelta(IList<JobDto> oldJobs, IDictionary<int, JobDto> helpJobs) {
794      bool found = false;
795      for (int i = 0; i < jobs.List.Count; i++) {
796        JobDto job = jobs.List[i];
797        for (int j = 0; j < oldJobs.Count; j++) {
798
799          JobDto jobold = oldJobs[j];
800
801          if (job.Id.Equals(jobold.Id)) {
802
803            found = true;
804            bool change = false;
805            if (job.State != jobold.State) {
806              change = true;
807            }
808            if (job.State != State.Offline) {
809              if ((!IsEqual(job.Client, jobold.Client)) || (job.State != jobold.State)
810                   || (job.Percentage != jobold.Percentage)) {
811                change = true;
812              }
813            } else if (job.DateCalculated != jobold.DateCalculated) {
814              change = true;
815            }
816            if (change) {
817              changes.Add(new Changes { Types = Type.Job, ID = job.Id, ChangeType = Change.Update, Position = i });
818            }
819
820            int removeAt = -1;
821            foreach (KeyValuePair<int, JobDto> kvp in helpJobs) {
822              if (job.Id.Equals(kvp.Value.Id)) {
823                removeAt = kvp.Key;
824                break;
825              }
826            }
827            if (removeAt >= 0) {
828              helpJobs.Remove(removeAt);
829            }
830            break;
831          }
832
833        }
834        if (found == false) {
835          changes.Add(new Changes { Types = Type.Job, ID = job.Id, ChangeType = Change.Create });
836        }
837        found = false;
838      }
839      foreach (KeyValuePair<int, JobDto> kvp in helpJobs) {
840        changes.Add(new Changes { Types = Type.Job, ID = kvp.Value.Id, ChangeType = Change.Delete, Position = kvp.Key });
841      }
842    }
843
844    #endregion
845
846    private void btn_prev_Click(object sender, EventArgs e) {
847      if (sender == btn_finishedJob_prev)
848        jdfFinished.Backward();
849      else if (sender == btn_calculatingJobs_prev)
850        jdfCalculating.Backward();
851      else if (sender == btn_offlinejob_prev) {
852        jdfOffline.Backward();
853      }
854    }
855
856    private void btn_next_Click(object sender, EventArgs e) {
857      if (sender == btn_finishedJob_next)
858        jdfFinished.Forward();
859      else if (sender == btn_calculatingJobs_next)
860        jdfCalculating.Forward();
861      else if (sender == btn_offlineJob_next) {
862        jdfOffline.Forward();
863      }
864    }
865
866    private void cmb_count_SelectedIndexChanged(object sender, EventArgs e) {
867      ComboBox box = (ComboBox) sender;
868      if (box.SelectedItem != null) {
869        int val;
870        if (Int32.TryParse(box.SelectedItem.ToString(), out val)) {
871          if (box == cmb_offlineJob_count) {
872            jdfOffline.NrOfEntriesOnPage = val;
873          }
874          else if (box == cmb_finishedJob_count) {
875            jdfFinished.NrOfEntriesOnPage = val;
876          }
877          else if (box == cmb_calculatingJob_count) {
878            jdfCalculating.NrOfEntriesOnPage = val;
879          }
880        }
881      }
882    }
883
884    private void lv_Jobs_SelectedIndexChanged(object sender, EventArgs e) {
885      ListView lv = (ListView) sender;
886      if(lv.SelectedItems.Count > 0) {
887        foreach (ListViewItem lvi in lv.SelectedItems) {
888          currentJob = (JobDto) lvi.Tag;
889          JobClicked();         
890        }
891      }
892    }
893  }
894}
Note: See TracBrowser for help on using the repository browser.