Free cookie consent management tool by TermsFeed Policy Generator

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

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

#663 Refactor

File size: 18.9 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;
34
35namespace HeuristicLab.Hive.Client.Console
36{
37
38  #region Delegates
39
40  public delegate void AppendTextDelegate(String message);
41  public delegate void OnDialogClosedDelegate(RecurrentEvent e);
42
43  #endregion
44
45  public partial class HiveClientConsole : Form
46  {
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 LogFileReader logFileReader;
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    public OnDialogClosedDelegate dialogClosedDelegate;
62
63    #endregion
64
65    #region Constructor
66
67    public HiveClientConsole()
68    {
69      InitializeComponent();
70      InitTimer();
71      ConnectToClient();
72      RefreshGui();
73      InitCalender();
74      InitLogFileReader();
75    }
76
77    #endregion
78
79    #region Methods
80
81    private void InitLogFileReader() {
82      logFileReader = new LogFileReader(Environment.CurrentDirectory + @"/Hive.log");
83      logFileReader.MoreData += new LogFileReader.MoreDataHandler(logFileReader_MoreData);
84      logFileReader.Start();
85    }
86
87    void logFileReader_MoreData(object sender, string newData) {
88
89      int maxChars = txtLog.MaxLength;
90      if (newData.Length > maxChars) {
91        newData = newData.Remove(0, newData.Length - maxChars);
92      }
93      int newLength = this.txtLog.Text.Length + newData.Length;
94      if (newLength > maxChars) {
95        this.txtLog.Text = this.txtLog.Text.Remove(0, newLength - (int)maxChars);
96      }
97      AppendText(newData);
98    }
99
100    private void InitTimer()
101    {
102      refreshTimer = new System.Windows.Forms.Timer();
103      refreshTimer.Interval = 1000;
104      refreshTimer.Tick += new EventHandler(refreshTimer_Tick);
105      refreshTimer.Start();
106    }
107
108    private void RefreshGui()
109    {
110      try
111      {
112        cccc.GetStatusInfosAsync();
113      }
114      catch (Exception ex)
115      {
116        refreshTimer.Stop();
117        DialogResult res = MessageBox.Show("Connection Error, check if Hive Client is running!", "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
118        if (res == DialogResult.OK)
119          this.Close();
120      }
121    }
122
123    private void ConnectToClient()
124    {
125      try
126      {
127        //changed by MB, 16.04.09
128        //cccc = new ClientConsoleCommunicatorClient(new NetTcpBinding(), new EndpointAddress(ENDPOINTADRESS));
129        cccc = new ClientConsoleCommunicatorClient(WcfSettings.GetBinding(), new EndpointAddress(ENDPOINTADRESS));
130        cccc.GetStatusInfosCompleted += new EventHandler<GetStatusInfosCompletedEventArgs>(cccc_GetStatusInfosCompleted);
131        cccc.GetCurrentConnectionCompleted += new EventHandler<GetCurrentConnectionCompletedEventArgs>(cccc_GetCurrentConnectionCompleted);
132      }
133      catch (Exception)
134      {
135        refreshTimer.Stop();
136        DialogResult res = MessageBox.Show("Connection Error, check if Hive Client is running!", "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
137        if (res == DialogResult.OK)
138          this.Close();
139      }
140    }
141
142    private void UpdateGraph(JobStatus[] jobs)
143    {
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      {
165        myPane.AddPieSlice(100, Color.Green, 0.1, "");
166      }
167      else
168      {
169        for (int i = 0; i < jobs.Length; i++)
170        {
171          allProgress += jobs[i].Progress;
172        }
173
174        done = allProgress / jobs.Length;
175
176        myPane.AddPieSlice(done, Color.Green, 0, "");
177        myPane.AddPieSlice(1 - done, Color.Red, 0, "");
178      }
179      //Hides the slice labels
180      PieItem.Default.LabelType = PieLabelType.None;
181
182      myPane.AxisChange();
183
184      pbGraph.Image = zgc.GetImage();
185    }
186
187    private void InitCalender()
188    {
189      dvOnline.StartDate = DateTime.Now;
190      dvOnline.OnNewAppointment += new EventHandler<NewAppointmentEventArgs>(DvOnline_OnNewAppointment);
191      dvOnline.OnResolveAppointments += new EventHandler<ResolveAppointmentsEventArgs>(DvOnline_OnResolveAppointments);
192    }
193
194    private Appointment CreateAppointment(DateTime startDate, DateTime endDate, bool allDay)
195    {
196      Appointment App = new Appointment();
197      App.StartDate = startDate;
198      App.EndDate = endDate;
199      App.AllDayEvent = allDay;
200      App.BorderColor = Color.Red;
201      App.Locked = true;
202      App.Subject = "Online";
203      App.Recurring = false;
204      return App;
205    }
206
207    private Appointment CreateAppointment(DateTime startDate, DateTime endDate, bool allDay, bool recurring, Guid recurringId)
208    {
209      Appointment App = new Appointment();
210      App.StartDate = startDate;
211      App.EndDate = endDate;
212      App.AllDayEvent = allDay;
213      App.BorderColor = Color.Red;
214      App.Locked = true;
215      App.Subject = "Online";
216      App.Recurring = recurring;
217      App.RecurringId = recurringId;
218      return App;
219    }
220
221    private void DeleteAppointment()
222    {
223      onlineTimes.Remove(dvOnline.SelectedAppointment);
224    }
225
226    private void DeleteRecurringAppointment(Guid recurringId)
227    {
228      onlineTimes.RemoveAll(a => a.RecurringId.ToString() == dvOnline.SelectedAppointment.RecurringId.ToString());
229    }
230
231    #endregion
232
233    #region Events
234
235    private void refreshTimer_Tick(object sender, EventArgs e)
236    {
237      RefreshGui();
238    }
239
240    private void cccc_GetCurrentConnectionCompleted(object sender, GetCurrentConnectionCompletedEventArgs e)
241    {
242      if (e.Error == null)
243      {
244        ConnectionContainer curConnection = e.Result;
245        tbIPAdress.Text = curConnection.IPAdress;
246        tbPort.Text = curConnection.Port.ToString();
247      }
248      else
249      {
250        refreshTimer.Stop();
251        DialogResult res = MessageBox.Show("Connection Error, check if Hive Client is running! - " + e.Error.Message, "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
252        if (res == DialogResult.OK)
253          this.Close();
254      }
255    }
256
257    private void cccc_GetStatusInfosCompleted(object sender, GetStatusInfosCompletedEventArgs e)
258    {
259
260      if (e.Error == null)
261      {
262        StatusCommons sc = e.Result;
263
264        lbGuid.Text = sc.ClientGuid.ToString();
265        lbConnectionStatus.Text = sc.Status.ToString();
266        lbJobdone.Text = sc.JobsDone.ToString();
267        lbJobsAborted.Text = sc.JobsAborted.ToString();
268        lbJobsFetched.Text = sc.JobsFetched.ToString();
269
270        this.Text = "Client Console (" + sc.Status.ToString() + ")";
271
272        ListViewItem curJobStatusItem;
273
274        if (sc.Jobs != null)
275        {
276          lvJobDetail.Items.Clear();
277          double progress;
278          foreach (JobStatus curJob in sc.Jobs)
279          {
280            curJobStatusItem = new ListViewItem(curJob.JobId.ToString());
281            curJobStatusItem.SubItems.Add(curJob.Since.ToString());
282            progress = curJob.Progress * 100;
283            curJobStatusItem.SubItems.Add(progress.ToString());
284            lvJobDetail.Items.Add(curJobStatusItem);
285          }
286          lvJobDetail.Sort();
287        }
288
289        UpdateGraph(sc.Jobs);
290
291        if (sc.Status == NetworkEnumWcfConnState.Connected || sc.Status == NetworkEnumWcfConnState.Loggedin)
292        {
293          btConnect.Enabled = false;
294          btnDisconnect.Enabled = true;
295          lbCs.Text = sc.ConnectedSince.ToString();
296          cccc.GetCurrentConnectionAsync();
297        }
298        else if (sc.Status == NetworkEnumWcfConnState.Disconnected)
299        {
300          btConnect.Enabled = true;
301          btnDisconnect.Enabled = false;
302          lbCs.Text = String.Empty;
303        }
304        else if (sc.Status == NetworkEnumWcfConnState.Failed)
305        {
306          btConnect.Enabled = true;
307          btnDisconnect.Enabled = false;
308          lbCs.Text = String.Empty;
309        }
310
311        cccc.GetCurrentConnection();
312      }
313      else
314      {
315        refreshTimer.Stop();
316        DialogResult res = MessageBox.Show("Connection Error, check if Hive Client is running! - " + e.Error.Message, "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
317        if (res == DialogResult.OK)
318          this.Close();
319      }
320    }
321
322    private void HiveClientConsole_Load(object sender, EventArgs e)
323    {
324      //nothing to do
325    }
326
327    private void AppendText(string message) {
328      if (this.txtLog.InvokeRequired) {
329        this.txtLog.Invoke(new
330          AppendTextDelegate(AppendText), new object[] { message });
331      } else {
332        this.txtLog.AppendText(message);
333      }
334    }
335
336    private void btConnect_Click(object sender, EventArgs e)
337    {
338      IPAddress ipAdress;
339      int port;
340      ConnectionContainer cc = new ConnectionContainer();
341      if (IPAddress.TryParse(tbIPAdress.Text, out ipAdress) && int.TryParse(tbPort.Text, out port))
342      {
343        cc.IPAdress = tbIPAdress.Text;
344        cc.Port = port;
345        cccc.SetConnectionAsync(cc);
346      }
347      else
348      {
349        MessageBox.Show("IP Adress and/or Port Error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
350      }
351    }
352
353    private void btnDisconnect_Click(object sender, EventArgs e)
354    {
355      cccc.DisconnectAsync();
356    }
357
358    private void btn_clientShutdown_Click(object sender, EventArgs e)
359    {
360      DialogResult res = MessageBox.Show("Do you really want to shutdown the Hive Client?", "Hive Client Console", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
361      if (res == DialogResult.Yes)
362      {
363        cccc.ShutdownClient();
364        this.Close();
365      }
366    }
367
368    private void btbDelete_Click(object sender, EventArgs e)
369    {
370      Appointment selectedAppointment = dvOnline.SelectedAppointment;
371      if (dvOnline.SelectedAppointment != null)
372      {
373        if (!selectedAppointment.Recurring)
374          DeleteAppointment();
375        else
376        {
377          DialogResult res = MessageBox.Show("Delete all events in this series?", "Delete recurrences", MessageBoxButtons.YesNo);
378          if (res != DialogResult.Yes)
379            DeleteAppointment();
380          else
381            DeleteRecurringAppointment(selectedAppointment.RecurringId);
382        }
383      }
384      dvOnline.Invalidate();
385    }
386
387    private void chbade_CheckedChanged(object sender, EventArgs e)
388    {
389      txttimeFrom.Visible = !chbade.Checked;
390      txttimeTo.Visible = !chbade.Checked;
391    }
392
393    private void dvOnline_OnSelectionChanged(object sender, EventArgs e)
394    {
395      btCreate.Enabled = true;
396      if (dvOnline.Selection == SelectionType.DateRange)
397      {
398        dtpFrom.Text = dvOnline.SelectionStart.ToShortDateString();
399        dtpTo.Text = dvOnline.SelectionEnd.Date.ToShortDateString();
400        txttimeFrom.Text = dvOnline.SelectionStart.ToShortTimeString();
401        txttimeTo.Text = dvOnline.SelectionEnd.ToShortTimeString();
402
403        btCreate.Text = "Save";
404      }
405
406      if (dvOnline.Selection == SelectionType.Appointment)
407      {
408
409        dtpFrom.Text = dvOnline.SelectedAppointment.StartDate.ToShortDateString();
410        dtpTo.Text = dvOnline.SelectedAppointment.EndDate.ToShortDateString();
411        txttimeFrom.Text = dvOnline.SelectedAppointment.StartDate.ToShortTimeString();
412        txttimeTo.Text = dvOnline.SelectedAppointment.EndDate.ToShortTimeString();
413
414        if (dvOnline.SelectedAppointment.Recurring)
415          btCreate.Enabled = false;
416        //also change the caption of the save button
417        btCreate.Text = "Save changes";
418      }
419
420      if (dvOnline.Selection == SelectionType.None)
421      {
422        //also change the caption of the save button
423        btCreate.Text = "Save";
424      }
425
426    }
427
428    private void Connection_KeyPress(object sender, KeyPressEventArgs e)
429    {
430      if (e.KeyChar == (char)Keys.Return)
431        btConnect_Click(null, null);
432    }
433
434    private void mcOnline_DateChanged(object sender, DateRangeEventArgs e)
435    {
436      dvOnline.StartDate = mcOnline.SelectionStart;
437    }
438
439    private bool CreateAppointment()
440    {
441      DateTime from, to;
442
443      if (!string.IsNullOrEmpty(dtpFrom.Text) && !string.IsNullOrEmpty(dtpTo.Text))
444      {
445        if (chbade.Checked)
446        {
447          //whole day appointment, only dates are visible
448          if (DateTime.TryParse(dtpFrom.Text + " " + txttimeFrom.Text, out from) && DateTime.TryParse(dtpTo.Text + " " + txttimeTo.Text, out to) && from < to)
449            onlineTimes.Add(CreateAppointment(from, to.AddDays(1), true));
450          else
451            MessageBox.Show("Incorrect date format", "Schedule Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
452        }
453        else if (!string.IsNullOrEmpty(txttimeFrom.Text) && !string.IsNullOrEmpty(txttimeTo.Text))
454        {
455          //Timeframe appointment
456          if (DateTime.TryParse(dtpFrom.Text + " " + txttimeFrom.Text, out from) && DateTime.TryParse(dtpTo.Text + " " + txttimeTo.Text, out to) && from < to)
457          {
458            if (from.Date == to.Date)
459              onlineTimes.Add(CreateAppointment(from, to, false));
460            else
461            {
462              //more than 1 day selected
463              while (from.Date != to.Date)
464              {
465                onlineTimes.Add(CreateAppointment(from, new DateTime(from.Year, from.Month, from.Day, to.Hour, to.Minute, 0, 0), false));
466                from = from.AddDays(1);
467              }
468              onlineTimes.Add(CreateAppointment(from, new DateTime(from.Year, from.Month, from.Day, to.Hour, to.Minute, 0, 0), false));
469            }
470          }
471          else
472            MessageBox.Show("Incorrect date format", "Schedule Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
473        }
474        dvOnline.Invalidate();
475        return true;
476      }
477      else
478      {
479        MessageBox.Show("Error in create appointment, please fill out all textboxes!", "Schedule Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
480        return false;
481      }
482    }
483
484    private void btCreate_Click(object sender, EventArgs e)
485    {
486      if (dvOnline.Selection != SelectionType.Appointment)
487      {
488        CreateAppointment();
489      }
490      else
491      {
492        //now we want to change an existing appointment
493        if (!dvOnline.SelectedAppointment.Recurring)
494        {
495          if (CreateAppointment())
496            DeleteAppointment();
497        }
498        else
499        {
500          //change recurring appointment
501          //check, if only selected appointment has to change or whole recurrence
502          DialogResult res = MessageBox.Show("Change all events in this series?", "Change recurrences", MessageBoxButtons.YesNo);
503          if (res != DialogResult.Yes)
504          {
505            if (CreateAppointment())
506              DeleteAppointment();
507          }
508          else
509            ChangeRecurrenceAppointment(dvOnline.SelectedAppointment.RecurringId);
510        }
511      }
512    }
513
514    private void ChangeRecurrenceAppointment(Guid recurringId)
515    {
516      List<Appointment> recurringAppointments = onlineTimes.Where(appointment => appointment.RecurringId == recurringId).ToList();
517      recurringAppointments.ForEach(appointment => appointment.StartDate = DateTime.Parse(appointment.StartDate.Date.ToString() + " " + txttimeFrom.Text));
518      recurringAppointments.ForEach(appointment => appointment.EndDate = DateTime.Parse(appointment.EndDate.Date.ToString() + " " + txttimeTo.Text));
519
520      DeleteRecurringAppointment(recurringId);
521      onlineTimes.AddRange(recurringAppointments);
522    }
523
524    private void DvOnline_OnResolveAppointments(object sender, ResolveAppointmentsEventArgs e)
525    {
526      List<Appointment> Apps = new List<Appointment>();
527
528      foreach (Appointment m_App in onlineTimes)
529        if ((m_App.StartDate >= e.StartDate) &&
530            (m_App.StartDate <= e.EndDate))
531          Apps.Add(m_App);
532      e.Appointments = Apps;
533    }
534
535    private void DvOnline_OnNewAppointment(object sender, NewAppointmentEventArgs e)
536    {
537      Appointment Appointment = new Appointment();
538
539      Appointment.StartDate = e.StartDate;
540      Appointment.EndDate = e.EndDate;
541
542      onlineTimes.Add(Appointment);
543    }
544
545    private void btnRecurrence_Click(object sender, EventArgs e)
546    {
547      Recurrence recurrence = new Recurrence();
548      recurrence.dialogClosedDelegate = new OnDialogClosedDelegate(this.DialogClosed);
549      recurrence.Show();
550    }
551
552    public void DialogClosed(RecurrentEvent e)
553    {
554      CreateDailyRecurrenceAppointments(e.DateFrom, e.DateTo, e.AllDay, e.IncWeeks, e.WeekDays);
555    }
556
557    private void CreateDailyRecurrenceAppointments(DateTime dateFrom, DateTime dateTo, bool allDay, int incWeek, HashSet<DayOfWeek> daysOfWeek) {
558      DateTime incDate = dateFrom;
559      Guid guid = Guid.NewGuid();
560
561      while (incDate.Date <= dateTo.Date) {
562        if (daysOfWeek.Contains(incDate.Date.DayOfWeek))
563          onlineTimes.Add(CreateAppointment(incDate, new DateTime(incDate.Year, incDate.Month, incDate.Day, dateTo.Hour, dateTo.Minute, 0), allDay, true, guid));
564        incDate = incDate.AddDays(1);
565      }
566
567      dvOnline.Invalidate();
568    }
569
570    #endregion
571
572  }
573}
Note: See TracBrowser for help on using the repository browser.