Free cookie consent management tool by TermsFeed Policy Generator

source: branches/Operator Architecture Refactoring/HeuristicLab.Hive.Client.Console/3.2/HiveClientConsole.cs @ 2498

Last change on this file since 2498 was 1949, checked in by whackl, 16 years ago

#663 refactor logViewer

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