source: trunk/sources/HeuristicLab.Hive.Client.Console/HiveClientConsole.cs @ 1145

Last change on this file since 1145 was 1145, checked in by whackl, 12 years ago

added shutdown button (#468)

File size: 14.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 System.Diagnostics;
31using System.Threading;
32using ZedGraph;
33using HeuristicLab.Hive.Client.Console.ClientService;
34using System.ServiceModel;
35using System.Net;
36using Calendar;
37
38namespace HeuristicLab.Hive.Client.Console {
39
40  #region Delegates
41
42  delegate void UpdateTextDelegate(EventLogEntry ev);
43
44  #endregion
45
46  public partial class HiveClientConsole : Form {
47
48    #region Declarations
49
50    private const string ENDPOINTADRESS = "net.tcp://127.0.0.1:8000/ClientConsole/ClientConsoleCommunicator";
51    private const string EVENTLOGNAME = "Hive Client";
52
53    private EventLog HiveClientEventLog;
54    private ClientConsoleCommunicatorClient cccc;
55    private System.Windows.Forms.Timer refreshTimer;
56    private ListViewColumnSorterDate lvwColumnSorter;
57
58    private List<Appointment> onlineTimes = new List<Appointment>();
59
60    #endregion
61
62    #region Constructor
63
64    public HiveClientConsole() {
65      InitializeComponent();
66      lvwColumnSorter = new ListViewColumnSorterDate();
67      lvLog.ListViewItemSorter = lvwColumnSorter;
68      lvwColumnSorter.SortColumn = 3;
69      lvwColumnSorter.Order = SortOrder.Descending;
70      InitTimer();
71      ConnectToClient();
72      RefreshGui();
73      GetEventLog();
74      InitCalender();
75    }
76
77    #endregion
78
79    #region Methods
80
81    private void InitTimer() {
82      refreshTimer = new System.Windows.Forms.Timer();
83      refreshTimer.Interval = 1000;
84      refreshTimer.Tick += new EventHandler(refreshTimer_Tick);
85      refreshTimer.Start();
86    }
87
88    private void RefreshGui() {
89      try {
90        cccc.GetStatusInfosAsync();
91      }
92      catch (Exception ex) {
93        refreshTimer.Stop();
94        DialogResult res = MessageBox.Show("Connection Error, check if Hive Client is running!", "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
95        if (res == DialogResult.OK)
96          this.Close();
97      }
98    }
99
100    private void ConnectToClient() {
101      try {
102        cccc = new ClientConsoleCommunicatorClient(new NetTcpBinding(), new EndpointAddress(ENDPOINTADRESS));
103        cccc.GetStatusInfosCompleted += new EventHandler<GetStatusInfosCompletedEventArgs>(cccc_GetStatusInfosCompleted);
104        cccc.GetCurrentConnectionCompleted += new EventHandler<GetCurrentConnectionCompletedEventArgs>(cccc_GetCurrentConnectionCompleted);
105      }
106      catch (Exception) {
107        refreshTimer.Stop();
108        DialogResult res = MessageBox.Show("Connection Error, check if Hive Client is running!", "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
109        if (res == DialogResult.OK)
110          this.Close();
111      }
112    }
113
114    private void GetEventLog() {
115      HiveClientEventLog = new EventLog(EVENTLOGNAME);
116      HiveClientEventLog.Source = EVENTLOGNAME;
117      HiveClientEventLog.EntryWritten += new EntryWrittenEventHandler(OnEntryWritten);
118      HiveClientEventLog.EnableRaisingEvents = true;
119
120      ListViewItem curEventLogEntry;
121
122      //databinding on listview?
123      if (HiveClientEventLog != null && HiveClientEventLog.Entries != null) {
124        foreach (EventLogEntry ele in HiveClientEventLog.Entries) {
125          curEventLogEntry = GenerateEventEntry(ele);
126          lvLog.Items.Add(curEventLogEntry);
127        }
128        lvJobDetail.Sort();
129      }
130    }
131
132    private ListViewItem GenerateEventEntry(EventLogEntry ele) {
133      ListViewItem curEventLogEntry;
134      curEventLogEntry = new ListViewItem("", 0);
135      if (ele.EntryType == EventLogEntryType.Error)
136        curEventLogEntry = new ListViewItem("", 1);
137      curEventLogEntry.SubItems.Add(ele.InstanceId.ToString());
138      curEventLogEntry.SubItems.Add(ele.Message);
139      curEventLogEntry.SubItems.Add(ele.TimeGenerated.ToString());
140      return curEventLogEntry;
141    }
142
143    private void UpdateGraph(JobStatus[] jobs) {
144      ZedGraphControl zgc = new ZedGraphControl();
145      GraphPane myPane = zgc.GraphPane;
146      myPane.GraphObjList.Clear();
147
148      myPane.Title.IsVisible = false;  // no title
149      myPane.Border.IsVisible = false; // no border
150      myPane.Chart.Border.IsVisible = false; // no border around the chart
151      myPane.XAxis.IsVisible = false;  // no x-axis
152      myPane.YAxis.IsVisible = false;  // no y-axis
153      myPane.Legend.IsVisible = false; // no legend
154
155      myPane.Fill.Color = this.BackColor;
156
157      myPane.Chart.Fill.Type = FillType.None;
158      myPane.Fill.Type = FillType.Solid;
159
160      double allProgress = 0;
161      double done = 0;
162
163      if (jobs.Length == 0) {
164        myPane.AddPieSlice(100, Color.Green, 0.1, "");
165      } else {
166        for (int i = 0; i < jobs.Length; i++) {
167          allProgress += jobs[i].Progress;
168        }
169
170        done = allProgress / jobs.Length;
171
172        myPane.AddPieSlice(done, Color.Green, 0, "");
173        myPane.AddPieSlice(1 - done, Color.Red, 0, "");
174      }
175      //Hides the slice labels
176      PieItem.Default.LabelType = PieLabelType.None;
177
178      myPane.AxisChange();
179
180      pbGraph.Image = zgc.GetImage();
181    }
182
183    private void InitCalender() {
184
185      dvOnline.StartDate = DateTime.Now;
186      dvOnline.OnNewAppointment += new EventHandler<NewAppointmentEventArgs>(DvOnline_OnNewAppointment);
187      dvOnline.OnResolveAppointments += new EventHandler<ResolveAppointmentsEventArgs>(DvOnline_OnResolveAppointments);
188    }
189
190    void DvOnline_OnResolveAppointments(object sender, ResolveAppointmentsEventArgs e) {
191      List<Appointment> Apps = new List<Appointment>();
192
193      foreach (Appointment m_App in onlineTimes)
194        if ((m_App.StartDate >= e.StartDate) &&
195            (m_App.StartDate <= e.EndDate))
196          Apps.Add(m_App);
197
198      e.Appointments = Apps;
199    }
200
201    void DvOnline_OnNewAppointment(object sender, NewAppointmentEventArgs e) {
202      Appointment Appointment = new Appointment();
203
204      Appointment.StartDate = e.StartDate;
205      Appointment.EndDate = e.EndDate;
206
207      onlineTimes.Add(Appointment);
208    }
209
210    #endregion
211
212    #region Events
213
214    private void refreshTimer_Tick(object sender, EventArgs e) {
215      RefreshGui();
216    }
217
218    private void cccc_GetCurrentConnectionCompleted(object sender, GetCurrentConnectionCompletedEventArgs e) {
219      if (e.Error == null) {
220        ConnectionContainer curConnection = e.Result;
221        tbIPAdress.Text = curConnection.IPAdress;
222        tbPort.Text = curConnection.Port.ToString();
223      } else {
224        refreshTimer.Stop();
225        DialogResult res = MessageBox.Show("Connection Error, check if Hive Client is running! - " + e.Error.Message, "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
226        if (res == DialogResult.OK)
227          this.Close();
228      }
229    }
230
231    private void cccc_GetStatusInfosCompleted(object sender, GetStatusInfosCompletedEventArgs e) {
232
233      if (e.Error == null) {
234        StatusCommons sc = e.Result;
235
236        lbGuid.Text = sc.ClientGuid.ToString();
237        lbConnectionStatus.Text = sc.Status.ToString();
238        lbJobdone.Text = sc.JobsDone.ToString();
239        lbJobsAborted.Text = sc.JobsAborted.ToString();
240        lbJobsFetched.Text = sc.JobsFetched.ToString();
241
242        this.Text = "Client Console (" + sc.Status.ToString() + ")";
243
244        ListViewItem curJobStatusItem;
245
246        if (sc.Jobs != null) {
247          lvJobDetail.Items.Clear();
248          double progress;
249          foreach (JobStatus curJob in sc.Jobs) {
250            curJobStatusItem = new ListViewItem(curJob.JobId.ToString());
251            curJobStatusItem.SubItems.Add(curJob.Since.ToString());
252            progress = curJob.Progress * 100;
253            curJobStatusItem.SubItems.Add(progress.ToString());
254            lvJobDetail.Items.Add(curJobStatusItem);
255          }
256          lvJobDetail.Sort();
257        }
258
259        UpdateGraph(sc.Jobs);
260
261        if (sc.Status == NetworkEnumWcfConnState.Connected) {
262          btConnect.Enabled = false;
263          btnDisconnect.Enabled = true;
264          lbCs.Text = sc.ConnectedSince.ToString();
265          cccc.GetCurrentConnectionAsync();
266        } else if (sc.Status == NetworkEnumWcfConnState.Disconnected) {
267          btConnect.Enabled = true;
268          btnDisconnect.Enabled = false;
269          lbCs.Text = String.Empty;
270        } else if (sc.Status == NetworkEnumWcfConnState.Failed) {
271          btConnect.Enabled = true;
272          btnDisconnect.Enabled = false;
273          lbCs.Text = String.Empty;
274        }
275      } else {
276        refreshTimer.Stop();
277        DialogResult res = MessageBox.Show("Connection Error, check if Hive Client is running! - " + e.Error.Message, "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
278        if (res == DialogResult.OK)
279          this.Close();
280      }
281    }
282
283    private void HiveClientConsole_Load(object sender, EventArgs e) {
284      //nothing to do
285    }
286
287    private void UpdateText(EventLogEntry ev) {
288      if (this.lvLog.InvokeRequired) {
289        this.lvLog.Invoke(new
290          UpdateTextDelegate(UpdateText), new object[] { ev });
291      } else {
292        ListViewItem curEventLogEntry = GenerateEventEntry(ev);
293        lvLog.Items.Add(curEventLogEntry);
294        lvJobDetail.Sort();
295      }
296    }
297
298    public void OnEntryWritten(object source, EntryWrittenEventArgs e) {
299      UpdateText(e.Entry);
300    }
301
302    private void HiveClientConsole_Resize(object sender, EventArgs e) {
303      //nothing to do
304    }
305
306    private void lvLog_DoubleClick(object sender, EventArgs e) {
307      ListViewItem lvi = lvLog.SelectedItems[0];
308      HiveEventEntry hee = new HiveEventEntry(lvi.SubItems[2].Text, lvi.SubItems[3].Text, lvi.SubItems[1].Text);
309
310      Form EventlogDetails = new EventLogEntryForm(hee);
311      EventlogDetails.Show();
312    }
313
314    private void btConnect_Click(object sender, EventArgs e) {
315      IPAddress ipAdress;
316      int port;
317      ConnectionContainer cc = new ConnectionContainer();
318      if (IPAddress.TryParse(tbIPAdress.Text, out ipAdress) && int.TryParse(tbPort.Text, out port)) {
319        cc.IPAdress = tbIPAdress.Text;
320        cc.Port = port;
321        cccc.SetConnectionAsync(cc);
322      } else {
323        MessageBox.Show("IP Adress and/or Port Error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
324      }
325    }
326
327    private void btnDisconnect_Click(object sender, EventArgs e) {
328      cccc.DisconnectAsync();
329    }
330
331    private void lvLog_ColumnClick(object sender, ColumnClickEventArgs e) {
332      // Determine if clicked column is already the column that is being sorted.
333      if (e.Column == lvwColumnSorter.SortColumn) {
334        // Reverse the current sort direction for this column.
335        if (lvwColumnSorter.Order == SortOrder.Ascending) {
336          lvwColumnSorter.Order = SortOrder.Descending;
337        } else {
338          lvwColumnSorter.Order = SortOrder.Ascending;
339        }
340      } else {
341        // Set the column number that is to be sorted; default to ascending.
342        lvwColumnSorter.SortColumn = e.Column;
343        lvwColumnSorter.Order = SortOrder.Ascending;
344      }
345
346      // Perform the sort with these new sort options.
347      lvLog.Sort();
348    }
349
350    private void btn_clientShutdown_Click(object sender, EventArgs e) {
351      DialogResult res = MessageBox.Show("Do you really want to shutdown the Hive Client?", "Hive Client Console", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
352      if (res == DialogResult.Yes) {
353        cccc.ShutdownClient();
354        this.Close();
355      }
356    }
357
358    #endregion
359
360    private void mcOnline_DateChanged(object sender, DateRangeEventArgs e) {
361      dvOnline.StartDate = mcOnline.SelectionStart;
362    }
363
364    private void btCreate_Click(object sender, EventArgs e) {
365
366      if (string.IsNullOrEmpty(txtFrom.Text)) {
367        Appointment App = new Appointment();
368        App.StartDate = dvOnline.SelectionStart;
369        App.EndDate = dvOnline.SelectionEnd;
370        App.BorderColor = Color.Red;
371        App.Locked = true;
372        App.Subject = "Online";
373        onlineTimes.Add(App);
374      } else if (string.IsNullOrEmpty(txtTimeTo.Text)) {
375        Appointment App = new Appointment();
376        App.StartDate = DateTime.Parse(txtFrom.Text);
377        App.EndDate = DateTime.Parse(txtTo.Text);
378        App.BorderColor = Color.Red;
379        App.Locked = true;
380        App.Subject = "Online";
381        onlineTimes.Add(App);
382      } else {
383        DateTime from = DateTime.Parse(txtFrom.Text);
384        DateTime to = DateTime.Parse(txtTo.Text);
385
386        while (from.Date != to.Date) {
387          Appointment App = new Appointment();
388          App.StartDate = new DateTime(from.Year, from.Month, from.Day, int.Parse(txttimeFrom.Text), 0,0);
389          App.EndDate = new DateTime(from.Year, from.Month, from.Day, int.Parse(txtTimeTo.Text), 0, 0);
390          App.BorderColor = Color.Red;
391          App.Locked = true;
392          App.Subject = "Online";
393          onlineTimes.Add(App);
394          from = from.AddDays(1);
395        }
396      }
397     
398      dvOnline.Invalidate();
399    }
400
401    private void btbDelete_Click(object sender, EventArgs e) {
402      if (dvOnline.SelectedAppointment != null)
403        onlineTimes.Remove(dvOnline.SelectedAppointment);
404      dvOnline.Invalidate();
405    }
406
407  }
408}
Note: See TracBrowser for help on using the repository browser.