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

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

update recurrence UI (#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      dvOnline.StartDate = DateTime.Now;
186      dvOnline.OnNewAppointment += new EventHandler<NewAppointmentEventArgs>(DvOnline_OnNewAppointment);
187      dvOnline.OnResolveAppointments += new EventHandler<ResolveAppointmentsEventArgs>(DvOnline_OnResolveAppointments);
188    }
189
190    private Appointment CreateAppointment(DateTime startDate, DateTime endDate, bool allDay) {
191      Appointment App = new Appointment();
192      App.StartDate = startDate;
193      App.EndDate = endDate;
194      App.AllDayEvent = allDay;
195      App.BorderColor = Color.Red;
196      App.Locked = true;
197      App.Subject = "Online";
198      return App;
199    }
200
201    //private ConvertToAppointments(List<
202
203    #endregion
204
205    #region Events
206
207    private void refreshTimer_Tick(object sender, EventArgs e) {
208      RefreshGui();
209    }
210
211    private void cccc_GetCurrentConnectionCompleted(object sender, GetCurrentConnectionCompletedEventArgs e) {
212      if (e.Error == null) {
213        ConnectionContainer curConnection = e.Result;
214        tbIPAdress.Text = curConnection.IPAdress;
215        tbPort.Text = curConnection.Port.ToString();
216      } else {
217        refreshTimer.Stop();
218        DialogResult res = MessageBox.Show("Connection Error, check if Hive Client is running! - " + e.Error.Message, "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
219        if (res == DialogResult.OK)
220          this.Close();
221      }
222    }
223
224    private void cccc_GetStatusInfosCompleted(object sender, GetStatusInfosCompletedEventArgs e) {
225
226      if (e.Error == null) {
227        StatusCommons sc = e.Result;
228
229        lbGuid.Text = sc.ClientGuid.ToString();
230        lbConnectionStatus.Text = sc.Status.ToString();
231        lbJobdone.Text = sc.JobsDone.ToString();
232        lbJobsAborted.Text = sc.JobsAborted.ToString();
233        lbJobsFetched.Text = sc.JobsFetched.ToString();
234
235        this.Text = "Client Console (" + sc.Status.ToString() + ")";
236
237        ListViewItem curJobStatusItem;
238
239        if (sc.Jobs != null) {
240          lvJobDetail.Items.Clear();
241          double progress;
242          foreach (JobStatus curJob in sc.Jobs) {
243            curJobStatusItem = new ListViewItem(curJob.JobId.ToString());
244            curJobStatusItem.SubItems.Add(curJob.Since.ToString());
245            progress = curJob.Progress * 100;
246            curJobStatusItem.SubItems.Add(progress.ToString());
247            lvJobDetail.Items.Add(curJobStatusItem);
248          }
249          lvJobDetail.Sort();
250        }
251
252        UpdateGraph(sc.Jobs);
253
254        if (sc.Status == NetworkEnumWcfConnState.Connected || sc.Status == NetworkEnumWcfConnState.Loggedin) {
255          btConnect.Enabled = false;
256          btnDisconnect.Enabled = true;
257          lbCs.Text = sc.ConnectedSince.ToString();
258          cccc.GetCurrentConnectionAsync();
259        } else if (sc.Status == NetworkEnumWcfConnState.Disconnected) {
260          btConnect.Enabled = true;
261          btnDisconnect.Enabled = false;
262          lbCs.Text = String.Empty;
263        } else if (sc.Status == NetworkEnumWcfConnState.Failed) {
264          btConnect.Enabled = true;
265          btnDisconnect.Enabled = false;
266          lbCs.Text = String.Empty;
267        }
268
269        cccc.GetCurrentConnection();
270      } else {
271        refreshTimer.Stop();
272        DialogResult res = MessageBox.Show("Connection Error, check if Hive Client is running! - " + e.Error.Message, "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
273        if (res == DialogResult.OK)
274          this.Close();
275      }
276    }
277
278    private void HiveClientConsole_Load(object sender, EventArgs e) {
279      //nothing to do
280    }
281
282    private void UpdateText(EventLogEntry ev) {
283      if (this.lvLog.InvokeRequired) {
284        this.lvLog.Invoke(new
285          UpdateTextDelegate(UpdateText), new object[] { ev });
286      } else {
287        ListViewItem curEventLogEntry = GenerateEventEntry(ev);
288        lvLog.Items.Add(curEventLogEntry);
289        lvJobDetail.Sort();
290      }
291    }
292
293    public void OnEntryWritten(object source, EntryWrittenEventArgs e) {
294      UpdateText(e.Entry);
295    }
296
297    private void lvLog_DoubleClick(object sender, EventArgs e) {
298      ListViewItem lvi = lvLog.SelectedItems[0];
299      HiveEventEntry hee = new HiveEventEntry(lvi.SubItems[2].Text, lvi.SubItems[3].Text, lvi.SubItems[1].Text);
300
301      Form EventlogDetails = new EventLogEntryForm(hee);
302      EventlogDetails.Show();
303    }
304
305    private void btConnect_Click(object sender, EventArgs e) {
306      IPAddress ipAdress;
307      int port;
308      ConnectionContainer cc = new ConnectionContainer();
309      if (IPAddress.TryParse(tbIPAdress.Text, out ipAdress) && int.TryParse(tbPort.Text, out port)) {
310        cc.IPAdress = tbIPAdress.Text;
311        cc.Port = port;
312        cccc.SetConnectionAsync(cc);
313      } else {
314        MessageBox.Show("IP Adress and/or Port Error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
315      }
316    }
317
318    private void btnDisconnect_Click(object sender, EventArgs e) {
319      cccc.DisconnectAsync();
320    }
321
322    private void lvLog_ColumnClick(object sender, ColumnClickEventArgs e) {
323      // Determine if clicked column is already the column that is being sorted.
324      if (e.Column == lvwColumnSorter.SortColumn) {
325        // Reverse the current sort direction for this column.
326        if (lvwColumnSorter.Order == SortOrder.Ascending) {
327          lvwColumnSorter.Order = SortOrder.Descending;
328        } else {
329          lvwColumnSorter.Order = SortOrder.Ascending;
330        }
331      } else {
332        // Set the column number that is to be sorted; default to ascending.
333        lvwColumnSorter.SortColumn = e.Column;
334        lvwColumnSorter.Order = SortOrder.Ascending;
335      }
336
337      // Perform the sort with these new sort options.
338      lvLog.Sort();
339    }
340
341    private void btn_clientShutdown_Click(object sender, EventArgs e) {
342      DialogResult res = MessageBox.Show("Do you really want to shutdown the Hive Client?", "Hive Client Console", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
343      if (res == DialogResult.Yes) {
344        cccc.ShutdownClient();
345        this.Close();
346      }
347    }
348
349    private void btbDelete_Click(object sender, EventArgs e) {
350      if (dvOnline.SelectedAppointment != null)
351        onlineTimes.Remove(dvOnline.SelectedAppointment);
352      dvOnline.Invalidate();
353    }
354
355    private void chbade_CheckedChanged(object sender, EventArgs e) {
356      //if (chbade.Checked) {
357      //  txttimeFrom.Visible = false;
358      //  txttimeTo.Visible = false;
359      //} else {
360      //  txttimeFrom.Visible = true;
361      //  txttimeTo.Visible = true;
362      //}
363      txttimeFrom.Visible = !chbade.Checked;
364      txttimeTo.Visible = !chbade.Checked;
365    }
366
367    private void dvOnline_OnSelectionChanged(object sender, EventArgs e) {
368      if (dvOnline.Selection == SelectionType.DateRange) {
369        dtpFrom.Text = dvOnline.SelectionStart.ToShortDateString();
370        dtpTo.Text = dvOnline.SelectionEnd.Date.ToShortDateString();
371        txttimeFrom.Text = dvOnline.SelectionStart.ToShortTimeString();
372        txttimeTo.Text = dvOnline.SelectionEnd.ToShortTimeString();
373      }
374    }
375
376    private void Connection_KeyPress(object sender, KeyPressEventArgs e) {
377      if (e.KeyChar == (char)Keys.Return)
378        btConnect_Click(null, null);
379    }
380
381    private void mcOnline_DateChanged(object sender, DateRangeEventArgs e) {
382      dvOnline.StartDate = mcOnline.SelectionStart;
383    }
384
385    private void btCreate_Click(object sender, EventArgs e) {
386      DateTime from, to;
387
388      if (!string.IsNullOrEmpty(dtpFrom.Text) && !string.IsNullOrEmpty(dtpTo.Text)) {
389        if (chbade.Checked) {
390          //whole day appointment, only dates are visible
391          if (DateTime.TryParse(dtpFrom.Text + " " + txttimeFrom.Text, out from) && DateTime.TryParse(dtpTo.Text + " " + txttimeTo.Text, out to) && from < to)
392            onlineTimes.Add(CreateAppointment(from, to.AddDays(1), true));
393          else
394            MessageBox.Show("Incorrect date format", "Schedule Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
395        } else if (!string.IsNullOrEmpty(txttimeFrom.Text) && !string.IsNullOrEmpty(txttimeTo.Text)) {
396          //Timeframe appointment
397          if (DateTime.TryParse(dtpFrom.Text + " " + txttimeFrom.Text, out from) && DateTime.TryParse(dtpTo.Text + " " + txttimeTo.Text, out to) && from < to) {
398            if (from.Date == to.Date)
399              onlineTimes.Add(CreateAppointment(from, to, false));
400            else {
401              //more than 1 day selected
402              while (from.Date != to.Date) {
403                onlineTimes.Add(CreateAppointment(from, new DateTime(from.Year, from.Month, from.Day, to.Hour, to.Minute, 0, 0), false));
404                from = from.AddDays(1);
405              }
406              onlineTimes.Add(CreateAppointment(from, new DateTime(from.Year, from.Month, from.Day, to.Hour, to.Minute, 0, 0), false));
407            }
408          } else
409            MessageBox.Show("Incorrect date format", "Schedule Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
410        }
411        dvOnline.Invalidate();
412      } else {
413        MessageBox.Show("Error in create appointment, please fill out all textboxes!", "Schedule Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
414      }
415    }
416
417    void DvOnline_OnResolveAppointments(object sender, ResolveAppointmentsEventArgs e) {
418      List<Appointment> Apps = new List<Appointment>();
419
420      foreach (Appointment m_App in onlineTimes)
421        if ((m_App.StartDate >= e.StartDate) &&
422            (m_App.StartDate <= e.EndDate))
423          Apps.Add(m_App);
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    private void btnRecurrence_Click(object sender, EventArgs e) {
437      Form recurrence = new Recurrence();
438      recurrence.Show();
439    }
440
441    #endregion
442
443  }
444}
Note: See TracBrowser for help on using the repository browser.