Free cookie consent management tool by TermsFeed Policy Generator

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

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

refactoring #663

File size: 21.5 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.Diagnostics;
25using System.Drawing;
26using System.Linq;
27using System.Net;
28using System.ServiceModel;
29using System.Windows.Forms;
30using Calendar;
31using HeuristicLab.Hive.Client.Console.ClientService;
32using ZedGraph;
33using HeuristicLab.Hive.Contracts;
34using System.Xml.Serialization;
35using System.IO;
36
37namespace HeuristicLab.Hive.Client.Console
38{
39
40  #region Delegates
41
42  //delegate to write text in the textbox from another process
43  public delegate void AppendTextDelegate(String message);
44
45  //delegate to remove text in the textbox from another process
46  public delegate void RemoveTextDelegate(int newLength, int maxChars);
47
48  //delegate fired, if a dialog is being closed
49  public delegate void OnDialogClosedDelegate(RecurrentEvent e);
50
51  #endregion
52
53  public partial class HiveClientConsole : Form
54  {
55
56    #region Declarations
57
58    private const string ENDPOINTADRESS = "net.tcp://127.0.0.1:8000/ClientConsole/ClientConsoleCommunicator";
59
60    private static bool isfired = false;
61    //the logfilereader
62    private LogFileReader logFileReader;
63
64    //communication with the client
65    private ClientConsoleCommunicatorClient clientCommunicator;
66
67    //the timer for refreshing the gui
68    private System.Windows.Forms.Timer refreshTimer;
69
70    //the list of appointments in the calender
71    [XmlArray("Appointments")]
72    [XmlArrayItem("Appointment", typeof(Appointment))]
73    public List<Appointment> onlineTimes = new List<Appointment>();
74
75    public OnDialogClosedDelegate dialogClosedDelegate;
76
77    #endregion
78
79    #region Constructor
80
81    public HiveClientConsole()
82    {
83      InitializeComponent();
84      InitTimer();
85      ConnectToClient();
86      RefreshGui();
87      InitCalender();
88      InitLogFileReader();
89    }
90
91    #endregion
92
93    #region Methods
94
95    #region Client connection
96
97    private void ConnectToClient()
98    {
99      try
100      {
101        clientCommunicator = new ClientConsoleCommunicatorClient(WcfSettings.GetBinding(), new EndpointAddress(ENDPOINTADRESS));
102        clientCommunicator.GetStatusInfosCompleted += new EventHandler<GetStatusInfosCompletedEventArgs>(clientCommunicator_GetStatusInfosCompleted);
103        clientCommunicator.GetCurrentConnectionCompleted += new EventHandler<GetCurrentConnectionCompletedEventArgs>(clientCommunicator_GetCurrentConnectionCompleted);
104        clientCommunicator.GetUptimeCalendarCompleted += new EventHandler<GetUptimeCalendarCompletedEventArgs>(clientCommunicator_GetUptimeCalendarCompleted);
105        clientCommunicator.SetUptimeCalendarCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(clientCommunicator_SetUptimeCalendarCompleted);
106      }
107      catch (Exception ex)
108      {
109        ManageFatalException("Connection Error, check if Hive Client is running!", "Connection Error", ex);
110      }
111    }
112
113    #endregion
114
115    #region Logging
116
117    private void InitLogFileReader()
118    {
119      logFileReader = new LogFileReader(Environment.CurrentDirectory + @"/Hive.log");
120      logFileReader.MoreData += new LogFileReader.MoreDataHandler(logFileReader_MoreData);
121      logFileReader.Start();
122    }
123
124    private void logFileReader_MoreData(object sender, string newData)
125    {
126      int maxChars = txtLog.MaxLength;
127      if (newData.Length > maxChars)
128      {
129        newData = newData.Remove(0, newData.Length - maxChars);
130      }
131      int newLength = this.txtLog.Text.Length + newData.Length;
132      if (newLength > maxChars)
133      {
134        RemoveText(newLength, maxChars);
135      }
136      AppendText(newData);
137    }
138
139    private void RemoveText(int newLength, int maxChars)
140    {
141      if (this.txtLog.InvokeRequired)
142      {
143        this.txtLog.Invoke(new
144          RemoveTextDelegate(RemoveText), new object[] { newLength, maxChars });
145      }
146      else
147      {
148        this.txtLog.Text = this.txtLog.Text.Remove(0, newLength - (int)maxChars);
149      }
150    }
151
152    private void AppendText(string message)
153    {
154      if (this.txtLog.InvokeRequired)
155      {
156        this.txtLog.Invoke(new
157          AppendTextDelegate(AppendText), new object[] { message });
158      }
159      else
160      {
161        this.txtLog.AppendText(message);
162      }
163    }
164
165    #endregion
166
167    #region Gui Refresh
168
169    private void InitTimer()
170    {
171      refreshTimer = new System.Windows.Forms.Timer();
172      refreshTimer.Interval = 1000;
173      refreshTimer.Tick += new EventHandler(refreshTimer_Tick);
174      refreshTimer.Start();
175    }
176
177    private void RefreshGui()
178    {
179      try
180      {
181        clientCommunicator.GetStatusInfosAsync();
182      }
183      catch (Exception ex)
184      {
185        ManageFatalException("Connection Error, check if Hive Client is running!", "Connection Error", ex);
186      }
187    }
188
189    private void UpdateGraph(JobStatus[] jobs)
190    {
191      ZedGraphControl zgc = new ZedGraphControl();
192      GraphPane myPane = zgc.GraphPane;
193      myPane.GraphObjList.Clear();
194
195      myPane.Title.IsVisible = false;  // no title
196      myPane.Border.IsVisible = false; // no border
197      myPane.Chart.Border.IsVisible = false; // no border around the chart
198      myPane.XAxis.IsVisible = false;  // no x-axis
199      myPane.YAxis.IsVisible = false;  // no y-axis
200      myPane.Legend.IsVisible = false; // no legend
201
202      myPane.Fill.Color = this.BackColor;
203
204      myPane.Chart.Fill.Type = FillType.None;
205      myPane.Fill.Type = FillType.Solid;
206
207      double allProgress = 0;
208      double done = 0;
209
210      if (jobs.Length == 0)
211      {
212        myPane.AddPieSlice(100, Color.Green, 0.1, "");
213      }
214      else
215      {
216        for (int i = 0; i < jobs.Length; i++)
217        {
218          allProgress += jobs[i].Progress;
219        }
220
221        done = allProgress / jobs.Length;
222
223        myPane.AddPieSlice(done, Color.Green, 0, "");
224        myPane.AddPieSlice(1 - done, Color.Red, 0, "");
225      }
226      //Hides the slice labels
227      PieItem.Default.LabelType = PieLabelType.None;
228
229      myPane.AxisChange();
230
231      pbGraph.Image = zgc.GetImage();
232    }
233
234    #region Events
235
236    private void refreshTimer_Tick(object sender, EventArgs e)
237    {
238      RefreshGui();
239    }
240
241    #endregion
242
243
244    #endregion
245
246    #region Calendar stuff
247
248    private void InitCalender()
249    {
250      dvOnline.StartDate = DateTime.Now;
251      dvOnline.OnNewAppointment += new EventHandler<NewAppointmentEventArgs>(dvOnline_OnNewAppointment);
252      dvOnline.OnResolveAppointments += new EventHandler<ResolveAppointmentsEventArgs>(dvOnline_OnResolveAppointments);
253
254      //get calender from client
255      clientCommunicator.GetUptimeCalendarAsync();
256    }
257
258    private bool CreateAppointment()
259    {
260      DateTime from, to;
261
262      if (!string.IsNullOrEmpty(dtpFrom.Text) && !string.IsNullOrEmpty(dtpTo.Text))
263      {
264        if (chbade.Checked)
265        {
266          //whole day appointment, only dates are visible
267          if (DateTime.TryParse(dtpFrom.Text, out from) && DateTime.TryParse(dtpTo.Text, out to) && from <= to)
268            onlineTimes.Add(CreateAppointment(from, to.AddDays(1), true));
269          else
270            MessageBox.Show("Incorrect date format", "Schedule Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
271        }
272        else if (!string.IsNullOrEmpty(txttimeFrom.Text) && !string.IsNullOrEmpty(txttimeTo.Text))
273        {
274          //Timeframe appointment
275          if (DateTime.TryParse(dtpFrom.Text + " " + txttimeFrom.Text, out from) && DateTime.TryParse(dtpTo.Text + " " + txttimeTo.Text, out to) && from < to)
276          {
277            if (from.Date == to.Date)
278              onlineTimes.Add(CreateAppointment(from, to, false));
279            else
280            {
281              //more than 1 day selected
282              while (from.Date != to.Date)
283              {
284                onlineTimes.Add(CreateAppointment(from, new DateTime(from.Year, from.Month, from.Day, to.Hour, to.Minute, 0, 0), false));
285                from = from.AddDays(1);
286              }
287              onlineTimes.Add(CreateAppointment(from, new DateTime(from.Year, from.Month, from.Day, to.Hour, to.Minute, 0, 0), false));
288            }
289          }
290          else
291            MessageBox.Show("Incorrect date format", "Schedule Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
292        }
293        dvOnline.Invalidate();
294        return true;
295      }
296      else
297      {
298        MessageBox.Show("Error in create appointment, please fill out all textboxes!", "Schedule Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
299        return false;
300      }
301    }
302
303    private Appointment CreateAppointment(DateTime startDate, DateTime endDate, bool allDay)
304    {
305      Appointment App = new Appointment();
306      App.StartDate = startDate;
307      App.EndDate = endDate;
308      App.AllDayEvent = allDay;
309      App.BorderColor = Color.Red;
310      App.Locked = true;
311      App.Subject = "Online";
312      App.Recurring = false;
313      return App;
314    }
315
316    private Appointment CreateAppointment(DateTime startDate, DateTime endDate, bool allDay, bool recurring, Guid recurringId)
317    {
318      Appointment App = new Appointment();
319      App.StartDate = startDate;
320      App.EndDate = endDate;
321      App.AllDayEvent = allDay;
322      App.BorderColor = Color.Red;
323      App.Locked = true;
324      App.Subject = "Online";
325      App.Recurring = recurring;
326      App.RecurringId = recurringId;
327      return App;
328    }
329
330    private void DeleteAppointment()
331    {
332      onlineTimes.Remove(dvOnline.SelectedAppointment);
333    }
334
335    private void DeleteRecurringAppointment(Guid recurringId)
336    {
337      onlineTimes.RemoveAll(a => a.RecurringId.ToString() == dvOnline.SelectedAppointment.RecurringId.ToString());
338    }
339
340    private void ChangeRecurrenceAppointment(Guid recurringId)
341    {
342      int hourfrom = int.Parse(txttimeFrom.Text.Substring(0, txttimeFrom.Text.IndexOf(':')));
343      int hourTo = int.Parse(txttimeTo.Text.Substring(0, txttimeTo.Text.IndexOf(':')));
344      List<Appointment> recurringAppointments = onlineTimes.Where(appointment => appointment.RecurringId == recurringId).ToList();
345      recurringAppointments.ForEach(appointment => appointment.StartDate = new DateTime(appointment.StartDate.Year, appointment.StartDate.Month, appointment.StartDate.Day, hourfrom, 0, 0));
346      recurringAppointments.ForEach(appointment => appointment.EndDate = new DateTime(appointment.EndDate.Year, appointment.EndDate.Month, appointment.EndDate.Day, hourTo, 0, 0));
347
348      DeleteRecurringAppointment(recurringId);
349      onlineTimes.AddRange(recurringAppointments);
350    }
351
352    public void DialogClosed(RecurrentEvent e)
353    {
354      CreateDailyRecurrenceAppointments(e.DateFrom, e.DateTo, e.AllDay, e.IncWeeks, e.WeekDays);
355    }
356
357    private void CreateDailyRecurrenceAppointments(DateTime dateFrom, DateTime dateTo, bool allDay, int incWeek, HashSet<DayOfWeek> daysOfWeek)
358    {
359      DateTime incDate = dateFrom;
360      Guid guid = Guid.NewGuid();
361
362      while (incDate.Date <= dateTo.Date)
363      {
364        if (daysOfWeek.Contains(incDate.Date.DayOfWeek))
365          onlineTimes.Add(CreateAppointment(incDate, new DateTime(incDate.Year, incDate.Month, incDate.Day, dateTo.Hour, dateTo.Minute, 0), allDay, true, guid));
366        incDate = incDate.AddDays(1);
367      }
368
369      dvOnline.Invalidate();
370    }
371
372    #region Calendar Events
373
374    private void btbDelete_Click(object sender, EventArgs e)
375    {
376      Appointment selectedAppointment = dvOnline.SelectedAppointment;
377      if (dvOnline.SelectedAppointment != null)
378      {
379        if (!selectedAppointment.Recurring)
380          DeleteAppointment();
381        else
382        {
383          DialogResult res = MessageBox.Show("Delete all events in this series?", "Delete recurrences", MessageBoxButtons.YesNo);
384          if (res != DialogResult.Yes)
385            DeleteAppointment();
386          else
387            DeleteRecurringAppointment(selectedAppointment.RecurringId);
388        }
389      }
390      dvOnline.Invalidate();
391    }
392
393    private void chbade_CheckedChanged(object sender, EventArgs e)
394    {
395      txttimeFrom.Visible = !chbade.Checked;
396      txttimeTo.Visible = !chbade.Checked;
397    }
398
399    private void dvOnline_OnSelectionChanged(object sender, EventArgs e)
400    {
401      //btCreate.Enabled = true;
402      if (dvOnline.Selection == SelectionType.DateRange)
403      {
404        dtpFrom.Text = dvOnline.SelectionStart.ToShortDateString();
405        dtpTo.Text = dvOnline.SelectionEnd.Date.ToShortDateString();
406        txttimeFrom.Text = dvOnline.SelectionStart.ToShortTimeString();
407        txttimeTo.Text = dvOnline.SelectionEnd.ToShortTimeString();
408
409        btCreate.Text = "Save";
410      }
411
412      if (dvOnline.Selection == SelectionType.Appointment)
413      {
414
415        dtpFrom.Text = dvOnline.SelectedAppointment.StartDate.ToShortDateString();
416        dtpTo.Text = dvOnline.SelectedAppointment.EndDate.ToShortDateString();
417        txttimeFrom.Text = dvOnline.SelectedAppointment.StartDate.ToShortTimeString();
418        txttimeTo.Text = dvOnline.SelectedAppointment.EndDate.ToShortTimeString();
419
420        if (dvOnline.SelectedAppointment.Recurring)
421          //btCreate.Enabled = false;
422          //also change the caption of the save button
423          btCreate.Text = "Save changes";
424      }
425
426      if (dvOnline.Selection == SelectionType.None)
427      {
428        //also change the caption of the save button
429        btCreate.Text = "Save";
430      }
431
432    }
433
434    private void mcOnline_DateChanged(object sender, DateRangeEventArgs e)
435    {
436      dvOnline.StartDate = mcOnline.SelectionStart;
437    }
438
439    private void btCreate_Click(object sender, EventArgs e)
440    {
441      if (dvOnline.Selection != SelectionType.Appointment)
442      {
443        CreateAppointment();
444      }
445      else
446      {
447        //now we want to change an existing appointment
448        if (!dvOnline.SelectedAppointment.Recurring)
449        {
450          if (CreateAppointment())
451            DeleteAppointment();
452        }
453        else
454        {
455          //change recurring appointment
456          //check, if only selected appointment has to change or whole recurrence
457          DialogResult res = MessageBox.Show("Change all events in this series?", "Change recurrences", MessageBoxButtons.YesNo);
458          if (res != DialogResult.Yes)
459          {
460            if (CreateAppointment())
461              DeleteAppointment();
462          }
463          else
464            ChangeRecurrenceAppointment(dvOnline.SelectedAppointment.RecurringId);
465        }
466      }
467      dvOnline.Invalidate();
468    }
469
470    private void btnRecurrence_Click(object sender, EventArgs e)
471    {
472      Recurrence recurrence = new Recurrence();
473      recurrence.dialogClosedDelegate = new OnDialogClosedDelegate(this.DialogClosed);
474      recurrence.Show();
475    }
476
477    private void btnSaveCal_Click(object sender, EventArgs e)
478    {
479      clientCommunicator.SetUptimeCalendarAsync(onlineTimes.ToArray());
480    }
481
482    private void dvOnline_OnResolveAppointments(object sender, ResolveAppointmentsEventArgs e)
483    {
484      List<Appointment> Apps = new List<Appointment>();
485
486      foreach (Appointment m_App in onlineTimes)
487        if ((m_App.StartDate >= e.StartDate) &&
488            (m_App.StartDate <= e.EndDate))
489          Apps.Add(m_App);
490      e.Appointments = Apps;
491    }
492
493    private void dvOnline_OnNewAppointment(object sender, NewAppointmentEventArgs e)
494    {
495      Appointment Appointment = new Appointment();
496
497      Appointment.StartDate = e.StartDate;
498      Appointment.EndDate = e.EndDate;
499
500      onlineTimes.Add(Appointment);
501    }
502
503    #endregion
504
505    #endregion
506
507    #region Client communicator events
508
509    void clientCommunicator_SetUptimeCalendarCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
510    {
511      if (e.Error == null)
512      {
513        MessageBox.Show("Calendar successfully saved!", "Calender", MessageBoxButtons.OK, MessageBoxIcon.Information);
514      }
515      else
516      {
517        MessageBox.Show("Error saving calender \n" + e.Error.ToString(), "Calender", MessageBoxButtons.OK, MessageBoxIcon.Error);
518      }
519    }
520
521    void clientCommunicator_GetUptimeCalendarCompleted(object sender, GetUptimeCalendarCompletedEventArgs e)
522    {
523      if (e.Error == null)
524      {
525        if (e.Result != null)
526        {
527          onlineTimes = e.Result.ToList<Appointment>();
528          onlineTimes.ForEach(a => a.BorderColor = Color.Red);
529        }
530        else
531        {
532          onlineTimes = new List<Appointment>();
533        }
534      }
535    }
536
537    private void clientCommunicator_GetCurrentConnectionCompleted(object sender, GetCurrentConnectionCompletedEventArgs e)
538    {
539      if (e.Error == null)
540      {
541        ConnectionContainer curConnection = e.Result;
542        tbIPAdress.Text = curConnection.IPAdress;
543        tbPort.Text = curConnection.Port.ToString();
544      }
545      else
546      {
547        ManageFatalException("Connection Error, check if Hive Client is running!", "Connection Error", null);
548      }
549    }
550
551    private void clientCommunicator_GetStatusInfosCompleted(object sender, GetStatusInfosCompletedEventArgs e)
552    {
553      if (e.Error == null)
554      {
555        StatusCommons sc = e.Result;
556
557        lbGuid.Text = sc.ClientGuid.ToString();
558        lbConnectionStatus.Text = sc.Status.ToString();
559        lbJobdone.Text = sc.JobsDone.ToString();
560        lbJobsAborted.Text = sc.JobsAborted.ToString();
561        lbJobsFetched.Text = sc.JobsFetched.ToString();
562
563        this.Text = "Client Console (" + sc.Status.ToString() + ")";
564
565        ListViewItem curJobStatusItem;
566
567        if (sc.Jobs != null)
568        {
569          lvJobDetail.Items.Clear();
570          double progress;
571          foreach (JobStatus curJob in sc.Jobs)
572          {
573            curJobStatusItem = new ListViewItem(curJob.JobId.ToString());
574            curJobStatusItem.SubItems.Add(curJob.Since.ToString());
575            progress = curJob.Progress * 100;
576            curJobStatusItem.SubItems.Add(progress.ToString());
577            lvJobDetail.Items.Add(curJobStatusItem);
578          }
579          lvJobDetail.Sort();
580        }
581
582        UpdateGraph(sc.Jobs);
583
584        if (sc.Status == NetworkEnumWcfConnState.Connected || sc.Status == NetworkEnumWcfConnState.Loggedin)
585        {
586          btConnect.Enabled = false;
587          btnDisconnect.Enabled = true;
588          lbCs.Text = sc.ConnectedSince.ToString();
589          clientCommunicator.GetCurrentConnectionAsync();
590        }
591        else if (sc.Status == NetworkEnumWcfConnState.Disconnected)
592        {
593          btConnect.Enabled = true;
594          btnDisconnect.Enabled = false;
595          lbCs.Text = String.Empty;
596        }
597        else if (sc.Status == NetworkEnumWcfConnState.Failed)
598        {
599          btConnect.Enabled = true;
600          btnDisconnect.Enabled = false;
601          lbCs.Text = String.Empty;
602        }
603
604        clientCommunicator.GetCurrentConnection();
605      }
606      else
607      {
608        ManageFatalException("Connection Error, check if Hive Client is running!", "Connection Error", null);
609      }
610    }
611
612    #endregion
613
614    #region Exception
615    private void ManageFatalException(string body, string caption, Exception e)
616    {
617      if (!isfired)
618      {
619        isfired = true;
620        refreshTimer.Stop();
621        DialogResult res = MessageBox.Show(body, caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
622        if (res == DialogResult.OK)
623          this.Close();
624      }
625    }
626
627    #endregion
628
629    #endregion
630
631    #region GUI Events
632
633    private void btConnect_Click(object sender, EventArgs e)
634    {
635      IPAddress ipAdress;
636      int port;
637      ConnectionContainer cc = new ConnectionContainer();
638      if (IPAddress.TryParse(tbIPAdress.Text, out ipAdress) && int.TryParse(tbPort.Text, out port))
639      {
640        cc.IPAdress = tbIPAdress.Text;
641        cc.Port = port;
642        clientCommunicator.SetConnectionAsync(cc);
643      }
644      else
645      {
646        MessageBox.Show("IP Adress and/or Port Error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
647      }
648    }
649
650    private void btnDisconnect_Click(object sender, EventArgs e)
651    {
652      clientCommunicator.DisconnectAsync();
653    }
654
655    private void btn_clientShutdown_Click(object sender, EventArgs e)
656    {
657      DialogResult res = MessageBox.Show("Do you really want to shutdown the Hive Client?", "Hive Client Console", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
658      if (res == DialogResult.Yes)
659      {
660        logFileReader.Stop();
661        clientCommunicator.ShutdownClient();
662        this.Close();
663      }
664    }
665
666    private void Connection_KeyPress(object sender, KeyPressEventArgs e)
667    {
668      if (e.KeyChar == (char)Keys.Return)
669        btConnect_Click(null, null);
670    }
671
672    #endregion
673
674  }
675}
Note: See TracBrowser for help on using the repository browser.