Free cookie consent management tool by TermsFeed Policy Generator

Changeset 2101 for trunk/sources


Ignore:
Timestamp:
06/25/09 14:18:47 (15 years ago)
Author:
whackl
Message:

refactoring #663

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/sources/HeuristicLab.Hive.Client.Console/3.2/HiveClientConsole.cs

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