Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 1181 was 1163, checked in by whackl, 16 years ago

added new scheduling features (#468)

File size: 15.8 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) {
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      } else {
268        refreshTimer.Stop();
269        DialogResult res = MessageBox.Show("Connection Error, check if Hive Client is running! - " + e.Error.Message, "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
270        if (res == DialogResult.OK)
271          this.Close();
272      }
273    }
274
275    private void HiveClientConsole_Load(object sender, EventArgs e) {
276      //nothing to do
277    }
278
279    private void UpdateText(EventLogEntry ev) {
280      if (this.lvLog.InvokeRequired) {
281        this.lvLog.Invoke(new
282          UpdateTextDelegate(UpdateText), new object[] { ev });
283      } else {
284        ListViewItem curEventLogEntry = GenerateEventEntry(ev);
285        lvLog.Items.Add(curEventLogEntry);
286        lvJobDetail.Sort();
287      }
288    }
289
290    public void OnEntryWritten(object source, EntryWrittenEventArgs e) {
291      UpdateText(e.Entry);
292    }
293
294    private void HiveClientConsole_Resize(object sender, EventArgs e) {
295      //nothing to do
296    }
297
298    private void lvLog_DoubleClick(object sender, EventArgs e) {
299      ListViewItem lvi = lvLog.SelectedItems[0];
300      HiveEventEntry hee = new HiveEventEntry(lvi.SubItems[2].Text, lvi.SubItems[3].Text, lvi.SubItems[1].Text);
301
302      Form EventlogDetails = new EventLogEntryForm(hee);
303      EventlogDetails.Show();
304    }
305
306    private void btConnect_Click(object sender, EventArgs e) {
307      IPAddress ipAdress;
308      int port;
309      ConnectionContainer cc = new ConnectionContainer();
310      if (IPAddress.TryParse(tbIPAdress.Text, out ipAdress) && int.TryParse(tbPort.Text, out port)) {
311        cc.IPAdress = tbIPAdress.Text;
312        cc.Port = port;
313        cccc.SetConnectionAsync(cc);
314      } else {
315        MessageBox.Show("IP Adress and/or Port Error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
316      }
317    }
318
319    private void btnDisconnect_Click(object sender, EventArgs e) {
320      cccc.DisconnectAsync();
321    }
322
323    private void lvLog_ColumnClick(object sender, ColumnClickEventArgs e) {
324      // Determine if clicked column is already the column that is being sorted.
325      if (e.Column == lvwColumnSorter.SortColumn) {
326        // Reverse the current sort direction for this column.
327        if (lvwColumnSorter.Order == SortOrder.Ascending) {
328          lvwColumnSorter.Order = SortOrder.Descending;
329        } else {
330          lvwColumnSorter.Order = SortOrder.Ascending;
331        }
332      } else {
333        // Set the column number that is to be sorted; default to ascending.
334        lvwColumnSorter.SortColumn = e.Column;
335        lvwColumnSorter.Order = SortOrder.Ascending;
336      }
337
338      // Perform the sort with these new sort options.
339      lvLog.Sort();
340    }
341
342    private void btn_clientShutdown_Click(object sender, EventArgs e) {
343      DialogResult res = MessageBox.Show("Do you really want to shutdown the Hive Client?", "Hive Client Console", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
344      if (res == DialogResult.Yes) {
345        cccc.ShutdownClient();
346        this.Close();
347      }
348    }
349
350    private void btbDelete_Click(object sender, EventArgs e) {
351      if (dvOnline.SelectedAppointment != null)
352        onlineTimes.Remove(dvOnline.SelectedAppointment);
353      dvOnline.Invalidate();
354    }
355
356    private void chbade_CheckedChanged(object sender, EventArgs e) {
357      if (chbade.Checked) {
358        txttimeFrom.Visible = false;
359        txtTimeTo.Visible = false;
360      } else {
361        txttimeFrom.Visible = true;
362        txtTimeTo.Visible = true;
363      }
364    }
365
366    private void dvOnline_OnSelectionChanged(object sender, EventArgs e) {
367      if (dvOnline.Selection == SelectionType.DateRange) {
368        txtFrom.Text = dvOnline.SelectionStart.ToShortDateString();
369        txtTo.Text = dvOnline.SelectionEnd.Date.ToShortDateString();
370        txttimeFrom.Text = dvOnline.SelectionStart.ToShortTimeString();
371        txtTimeTo.Text = dvOnline.SelectionEnd.ToShortTimeString();
372      }
373    }
374
375    private void Connection_KeyPress(object sender, KeyPressEventArgs e) {
376      if (e.KeyChar == (char)Keys.Return)
377        btConnect_Click(null, null);
378    }
379
380    private void mcOnline_DateChanged(object sender, DateRangeEventArgs e) {
381      dvOnline.StartDate = mcOnline.SelectionStart;
382    }
383
384    private void btCreate_Click(object sender, EventArgs e) {
385      DateTime from, to;
386
387      if (!string.IsNullOrEmpty(txtFrom.Text) && !string.IsNullOrEmpty(txtTo.Text)) {
388        if (chbade.Checked) {
389          //whole day appointment, only dates are visible
390          if (DateTime.TryParse(txtFrom.Text + " " + txttimeFrom.Text, out from) && DateTime.TryParse(txtTo.Text + " " + txtTimeTo.Text, out to) && from < to)
391            onlineTimes.Add(CreateAppointment(from, to.AddDays(1), true));
392          else
393            MessageBox.Show("Incorrect date format", "Schedule Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
394        } else if (!string.IsNullOrEmpty(txttimeFrom.Text) && !string.IsNullOrEmpty(txtTimeTo.Text)) {
395          //Timeframe appointment
396          if (DateTime.TryParse(txtFrom.Text + " " + txttimeFrom.Text, out from) && DateTime.TryParse(txtTo.Text + " " + txtTimeTo.Text, out to) && from < to) {
397            if (from.Date == to.Date)
398              onlineTimes.Add(CreateAppointment(from, to, false));
399            else {
400              //more than 1 day selected
401              while (from.Date != to.Date) {
402                onlineTimes.Add(CreateAppointment(from, new DateTime(from.Year, from.Month, from.Day, to.Hour, to.Minute, 0, 0), false));
403                from = from.AddDays(1);
404              }
405              onlineTimes.Add(CreateAppointment(from, new DateTime(from.Year, from.Month, from.Day, to.Hour, to.Minute, 0, 0), false));
406            }
407          } else
408            MessageBox.Show("Incorrect date format", "Schedule Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
409        }
410        dvOnline.Invalidate();
411      } else {
412        MessageBox.Show("Error in create appointment, please fill out all textboxes!", "Schedule Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
413      }
414    }
415
416    void DvOnline_OnResolveAppointments(object sender, ResolveAppointmentsEventArgs e) {
417      List<Appointment> Apps = new List<Appointment>();
418
419      foreach (Appointment m_App in onlineTimes)
420        if ((m_App.StartDate >= e.StartDate) &&
421            (m_App.StartDate <= e.EndDate))
422          Apps.Add(m_App);
423
424      e.Appointments = Apps;
425    }
426
427    void DvOnline_OnNewAppointment(object sender, NewAppointmentEventArgs e) {
428      Appointment Appointment = new Appointment();
429
430      Appointment.StartDate = e.StartDate;
431      Appointment.EndDate = e.EndDate;
432
433      onlineTimes.Add(Appointment);
434    }
435
436    #endregion
437  }
438}
Note: See TracBrowser for help on using the repository browser.