Exemple #1
0
        /// <summary>
        /// Perform the update of the Google Calendar
        /// </summary>
        public static void UpdateGoogleCalendar()
        {
            if (HaveRequiredData())
            {
                UpdateProgramStatus("Performing calendar update...");
                log.Info("Starting the update Process...");

                // Show tool tip in case application is minimised to tray
                mainForm.notifyIcon.BalloonTipIcon  = ToolTipIcon.Info;
                mainForm.notifyIcon.BalloonTipTitle = "Performing Update";
                mainForm.notifyIcon.BalloonTipText  = "Updating the Google Calendar with latest Salon Appointments...";
                mainForm.notifyIcon.ShowBalloonTip(5000);

                // Get Google Calendar Events
                if (GCalHelper.googleCalEvents == null)
                {
                    GCalHelper.GetYearlyEvents(_calendarOwner, _calendarId, _calendarYear, null);
                }

                List <GCalEventItem> currentGoogEvents = GCalHelper.googleCalEvents;

                // Load Values From Salon Calendar
                DBHelper.InitData(_calendarYear.Year);
                List <GCalEventItem> currentSalonEvents = DBHelper.ConvertSQLTicketsToEvents();
                if (currentSalonEvents != null && currentSalonEvents.Count > 0)
                {
                    // get New Events to create
                    if (currentGoogEvents != null && currentGoogEvents.Count > 0)
                    {
                        newEvents = (List <GCalEventItem>)currentSalonEvents.Except(currentGoogEvents).ToList();
                    }
                    else
                    {
                        newEvents = currentSalonEvents;
                    }

                    // get events that need to delete
                    if (currentGoogEvents != null && currentGoogEvents.Count > 0)
                    {
                        deletedEvents = (List <GCalEventItem>)currentGoogEvents.Except(currentSalonEvents).ToList();
                    }
                    else
                    {
                        deletedEvents = new List <GCalEventItem>();
                    }

                    // get Events that need to update
                    if (currentGoogEvents != null && currentGoogEvents.Count > 0)
                    {
                        List <GCalEventItem> potentialUpdatedEvents = (List <GCalEventItem>)currentSalonEvents.Except(newEvents).ToList();
                        foreach (GCalEventItem e in potentialUpdatedEvents)
                        {
                            GCalEventItem ge = currentGoogEvents.Find(x => x.SalonCalendarId == e.SalonCalendarId);
                            if (ge != null)
                            {
                                e.EventId = ge.EventId;
                            }
                        }

                        List <GCalEventItem> noGoogleIdEvents = potentialUpdatedEvents.FindAll(x => x.EventId == null).ToList();
                        if (noGoogleIdEvents != null && noGoogleIdEvents.Count > 0)
                        {
                            newEvents = (List <GCalEventItem>)newEvents.Concat(noGoogleIdEvents.Except(newEvents)).ToList();
                            potentialUpdatedEvents = (List <GCalEventItem>)potentialUpdatedEvents.Except(noGoogleIdEvents).ToList();
                        }

                        List <GCalEventItem> unchangedEvents = new List <GCalEventItem>();
                        foreach (var ev in potentialUpdatedEvents)
                        {
                            var entryToCheck = currentGoogEvents.FirstOrDefault(x => x.SalonCalendarId == ev.SalonCalendarId);
                            if (entryToCheck != null)
                            {
                                if (entryToCheck.AppointmentType != ev.AppointmentType ||
                                    entryToCheck.Client != ev.Client ||
                                    entryToCheck.StaffMember != ev.StaffMember ||
                                    entryToCheck.StartTime != ev.StartTime ||
                                    entryToCheck.EndTime != ev.EndTime ||
                                    entryToCheck.DurationMinutes != ev.DurationMinutes)
                                {
                                    // need to update so leave in list
                                    log.Debug("Need to update event ->" + entryToCheck.SalonCalendarId);
                                }
                                else
                                {
                                    unchangedEvents.Add(entryToCheck);
                                }
                            }
                        }

                        updatedEvents = (List <GCalEventItem>)potentialUpdatedEvents.Except(unchangedEvents).ToList();
                    }
                    else
                    {
                        updatedEvents = new List <GCalEventItem>();
                    }

                    GCalHelper.UpdateGoogleCalendar(_calendarOwner, _calendarId, newEvents, updatedEvents, deletedEvents);

                    log.Info("Finished the update Process...");
                    UpdateProgramStatus("Calendar update completed - " + DateTime.Now.ToString("dd/MM/yyyy h:mm tt"));

                    // Show tool tip in case application is minimised to tray
                    mainForm.notifyIcon.BalloonTipIcon  = ToolTipIcon.Info;
                    mainForm.notifyIcon.BalloonTipTitle = "Update Complete";
                    mainForm.notifyIcon.BalloonTipText  = "Update with latest Salon Appointments complete - " + DateTime.Now.ToString("dd/MM/yyyy h:mm tt");
                    mainForm.notifyIcon.ShowBalloonTip(5000);
                }
                else
                {
                    log.Info("Finished the update Process...");
                    UpdateProgramStatus("Calendar update error - " + DateTime.Now.ToString("dd/MM/yyyy h:mm tt"));

                    // Show tool tip in case application is minimised to tray
                    mainForm.notifyIcon.BalloonTipIcon  = ToolTipIcon.Info;
                    mainForm.notifyIcon.BalloonTipTitle = "Update Error";
                    mainForm.notifyIcon.BalloonTipText  = "Could not update with latest Salon Appointments - " + DateTime.Now.ToString("dd/MM/yyyy h:mm tt");
                    mainForm.notifyIcon.ShowBalloonTip(5000);
                }
            }
            else
            {
                log.Error("Could not perform update as required data has not been set.");
                MessageBox.Show("Please provide the Calendar Owner and other Calendar details before updating.");
            }
        }
        /// <summary>
        /// Get the current Google calendar events for a year
        /// </summary>
        /// <param name="owner">Google account</param>
        /// <param name="calendarId">Calendar ID</param>
        /// <param name="updateYear">Year to get events for</param>
        /// <param name="pageToken">Whether there are more pages of events</param>
        public static void GetYearlyEvents(string owner, string calendarId, DateTime updateYear, string pageToken)
        {
            if (string.IsNullOrEmpty(pageToken))
            {
                log.Info("Starting Retrieval of Events from " + owner + "'s Google Calendar (" + calendarId + ") for " + updateYear.Year);
            }

            int year = updateYear.Year;

            DateTime minTime = DateTime.Parse("1/1/" + year + " 00:00:00");
            DateTime maxTime = DateTime.Parse("1/1/" + (year + 2) + " 00:00:00");

            // Define parameters of request.
            EventsResource.ListRequest request = GetCalendarService(owner).Events.List(calendarId);

            request.ShowDeleted  = false;
            request.SingleEvents = true;
            request.MaxResults   = 2500;
            request.TimeMin      = minTime;
            request.TimeMax      = maxTime;
            request.OrderBy      = EventsResource.ListRequest.OrderByEnum.StartTime;
            if (!string.IsNullOrEmpty(pageToken))
            {
                request.PageToken = pageToken;
            }

            // List events.
            Events events = request.Execute();

            if (events.Items != null && events.Items.Count > 0)
            {
                if (googleCalEvents == null)
                {
                    googleCalEvents = new List <GCalEventItem>();
                }

                foreach (var eventItem in events.Items)
                {
                    GCalEventItem entry = new GCalEventItem();

                    entry.EventId = eventItem.Id;

                    string when = eventItem.Start.DateTime.ToString();
                    if (string.IsNullOrEmpty(when))
                    {
                        when = eventItem.Start.Date;
                    }

                    string ending = eventItem.End.DateTime.ToString();
                    if (string.IsNullOrEmpty(ending))
                    {
                        ending = eventItem.End.Date;
                    }

                    entry.StartTime = DateTime.Parse(when);
                    entry.EndTime   = DateTime.Parse(ending);

                    entry.DurationMinutes = (entry.EndTime - entry.StartTime).TotalMinutes;

                    List <KeyValuePair <string, string> > extraProps = eventItem.ExtendedProperties.Private__.ToList();
                    string key         = "staffMember";
                    string staffMember = (from kvp in extraProps where kvp.Key == key select kvp.Value).Single();

                    if (!string.IsNullOrEmpty(staffMember))
                    {
                        if (staffMember.ToUpper().Equals(((NaNStaff.Employees) 2).ToString()))
                        {
                            entry.StaffMember = NaNStaff.Employees.LYSHAIE;
                        }
                        else
                        {
                            entry.StaffMember = NaNStaff.Employees.KOULA;
                        }
                    }

                    key = "appointmentType";
                    string appointmentType = (from kvp in extraProps where kvp.Key == key select kvp.Value).Single();
                    if (!string.IsNullOrEmpty(appointmentType))
                    {
                        entry.AppointmentType = appointmentType;
                    }

                    key = "client";
                    string client = (from kvp in extraProps where kvp.Key == key select kvp.Value).Single();
                    if (!string.IsNullOrEmpty(client))
                    {
                        entry.Client = client;
                    }

                    key = "salonCalId";
                    string salonCalId = (from kvp in extraProps where kvp.Key == key select kvp.Value).Single();
                    if (!string.IsNullOrEmpty(salonCalId))
                    {
                        entry.SalonCalendarId = int.Parse(salonCalId);
                    }

                    googleCalEvents.Add(entry);
                }
            }
            else
            {
                log.Info("No upcoming events found in Google Calendar.");
            }

            // Response has more pages of events, get the next page for processing
            if (!string.IsNullOrEmpty(events.NextPageToken))
            {
                GetYearlyEvents(owner, calendarId, updateYear, events.NextPageToken);
            }

            log.Info("Finished Retrieval of Events from " + owner + "'s Google Calendar (" + calendarId + ") for " + updateYear.Year);
        }
Exemple #3
0
        /// <summary>
        /// Convert SQL appointment data to custom event data structure GCalEventItem
        /// </summary>
        /// <returns>Events from the DB</returns>
        public static List <GCalEventItem> ConvertSQLTicketsToEvents()
        {
            log.Info("Starting Reading of Salon SQL Calendar Data");

            List <GCalEventItem> ticketEvents = new List <GCalEventItem>();

            if (ds != null && ds.Tables.Count > 0)
            {
                try
                {
                    DataTable tickets       = ds.Tables["Tickets"];
                    var       ticketIDQuery = from ticket in tickets.AsEnumerable() select ticket.Field <int>("id");

                    List <int> ticketIDs = ticketIDQuery.GroupBy(x => x).Select(y => y.First()).OrderBy(z => z).ToList();

                    foreach (int ticketID in ticketIDs)
                    {
                        GCalEventItem newEvent = new GCalEventItem();

                        var appointmentQuery = from ticket in tickets.AsEnumerable()
                                               where ticket.Field <int>("id") == ticketID
                                               select new
                        {
                            TicketId           = ticket.Field <int>("id"),
                            ClientId           = ticket.Field <int>("clientId"),
                            FirstName          = ticket.Field <string>("clientFirstName"),
                            LastName           = ticket.Field <string>("clientLastName"),
                            Employee           = ticket.Field <string>("staff"),
                            StartDate          = ticket.Field <DateTime>("startDate"),
                            EndDate            = ticket.Field <DateTime>("endDate"),
                            StartTime          = ticket.Field <DateTime>("startTime"),
                            EndTime            = ticket.Field <DateTime>("endTime"),
                            ServiceDescription = ticket.Field <string>("serviceDescription")
                        };

                        newEvent.SalonCalendarId = ticketID;

                        newEvent.AppointmentType = RemoveSpecialCharacters(appointmentQuery.Select(x => x.ServiceDescription).First());
                        string clientName = RemoveSpecialCharacters(appointmentQuery.Select(x => x.FirstName).First().Trim());
                        if (!string.IsNullOrEmpty(appointmentQuery.Select(x => x.LastName).First()))
                        {
                            clientName += " ";
                            clientName += RemoveSpecialCharacters(appointmentQuery.Select(x => x.LastName).First().Trim());
                        }

                        newEvent.Client = clientName;

                        string employee = RemoveSpecialCharacters(appointmentQuery.Select(x => x.Employee).FirstOrDefault().ToLower().Trim());
                        if (string.IsNullOrEmpty(employee))
                        {
                            employee = ((NaNStaff.Employees) 0).ToString().ToLower();
                        }

                        switch (employee.ToLower())
                        {
                        case "lyshaie white":
                            newEvent.StaffMember = NaNStaff.Employees.LYSHAIE;
                            break;

                        default:
                            newEvent.StaffMember = NaNStaff.Employees.KOULA;
                            break;
                        }

                        DateTime appStart     = appointmentQuery.Min(x => x.StartDate);
                        DateTime appStartTime = appointmentQuery.Min(x => x.StartTime);
                        DateTime appEnd       = appointmentQuery.Max(x => x.EndDate);
                        DateTime appEndTime   = appointmentQuery.Max(x => x.EndTime);

                        newEvent.StartTime = DateTime.Parse(appStart.ToShortDateString() + " " + appStartTime.TimeOfDay);
                        newEvent.EndTime   = DateTime.Parse(appEnd.ToShortDateString() + " " + appEndTime.TimeOfDay);

                        newEvent.DurationMinutes = (newEvent.EndTime - newEvent.StartTime).TotalMinutes;

                        ticketEvents.Add(newEvent);
                    }
                }
                catch (Exception e)
                {
                    log.Error("Error in SQL Read : " + e.Message);
                }
            }
            else
            {
                // Error have not initialized Data
                log.Error("ERROR: Reading of SQL Data attempted before initialisation has been performed.");
            }

            log.Info("Finished Reading Salon SQL Calendar Data");
            return(ticketEvents);
        }