Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Hive_Milestone2/sources/HeuristicLab.Hive.Client.Console/3.2/HiveClientConsole.cs @ 4501

Last change on this file since 4501 was 1833, checked in by kgrading, 16 years ago

removed windows eventlog property (#467)

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