Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 1259 was 1259, checked in by whackl, 15 years ago

fixed some bugs (#468)

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