Exemplo n.º 1
0
        private void display_ContextMenuOpening(object sender, ContextMenuEventArgs e)
        {
            try
            {
                Appointment appointment = AppointmentDatabase.GetAppointment(_appointment.ID);
                privateMenuItem.IsChecked = appointment.Private;

                for (int i = 0; i < 5; i++)
                {
                    (showAsMenuItem.Items[i] as MenuItem).IsChecked = i == (int)appointment.ShowAs;
                }

                UpdateGetDirectionsMenu(appointment);
            }
            catch { }
        }
Exemplo n.º 2
0
        public DateTime?GetNextRecurrence(DateTime reference, DateTime?maxValue = null)
        {
            if (_repeatId != null)
            {
                return(AppointmentDatabase.GetAppointment(_repeatId).GetNextRecurrence(reference, maxValue));
            }

            reference = reference.Date;

            if (maxValue.HasValue)
            {
                maxValue = maxValue.Value.Date.AddDays(1);
            }

            DateTime?representingDate;

            return(_recurrence.GetNextRecurrence(_startDate.Date, _allDay ? _endDate : _endDate.Date.AddDays(1), _allDay,
                                                 reference, out representingDate, maxValue));
        }
Exemplo n.º 3
0
        /// <summary>
        /// Refreshes all appointments with the given ID.
        /// </summary>
        /// <param name="id"></param>
        public void Refresh(string id)
        {
            foreach (DayDetail each in stackPanel.Children)
            {
                Appointment appt = each.Appointment;

                if (appt.ID == id || appt.RepeatID == id)
                {
                    if (appt.IsRepeating && appt.RepeatID == null)
                    {
                        each.Appointment = AppointmentDatabase.GetRecurringAppointment(id);
                    }
                    else
                    {
                        each.Appointment = AppointmentDatabase.GetAppointment(appt.ID);
                    }

                    each.InitializeDisplay();
                    return;
                }
            }

            foreach (DayDetail each in clockGrid.Items)
            {
                Appointment appt = each.Appointment;

                if (appt.ID == id || appt.RepeatID == id)
                {
                    if (appt.IsRepeating && appt.RepeatID == null)
                    {
                        each.Appointment = AppointmentDatabase.GetRecurringAppointment(id);
                    }
                    else
                    {
                        each.Appointment = AppointmentDatabase.GetAppointment(appt.ID);
                    }

                    each.InitializeDisplay();
                    return;
                }
            }
        }
Exemplo n.º 4
0
        private void ShowSelection(SearchResultUI item)
        {
            SearchResult result = item.Result;

            if (result.RepresentingObject == RepresentingObject.Appointment)
            {
                //Appointment appointment = AppointmentDatabase.GetAppointment(result.ID);

                //if (!appointment.IsRepeating)
                if (!result.Recurring)
                {
                    NavigateAppointmentEvent(new NavigateAppointmentEventArgs(result.Date.Value, result.ID));
                }
                else
                {
                    Appointment appointment = AppointmentDatabase.GetAppointment(result.ID);

                    DateTime now = DateTime.Now.Date;

                    DateTime?date = appointment.GetNextRecurrence(now.AddDays(-1));

                    if (date == null)
                    {
                        date = appointment.GetPreviousRecurrence(now.AddDays(1));
                    }

                    NavigateAppointmentEvent(new NavigateAppointmentEventArgs(date.Value, result.ID));
                }
            }
            else if (result.RepresentingObject == RepresentingObject.Contact)
            {
                NavigateContactEvent(new NavigateContactEventArgs(result.ID));
            }
            else if (result.RepresentingObject == RepresentingObject.Task)
            {
                NavigateTaskEvent(new NavigateTaskEventArgs(result.ID));
            }
            else if (result.RepresentingObject == RepresentingObject.Note)
            {
                NavigateNoteEvent(new NavigateNoteEventArgs(result.ID));
            }
        }
Exemplo n.º 5
0
        public static void DownloadMergeCalendar(IEnumerable <EventEntry> entries, string owner, CalendarService calendarService, string feedUrl, CancellationToken token)
        {
            if (entries == null)
            {
                return;
            }

            foreach (EventEntry each in entries)
            {
                for (int i = 0; i < MaxTries; i++)
                {
                    try
                    {
                        if (each.Status.Value != EventEntry.EventStatus.CANCELED_VALUE)
                        {
                            if (!each.IsDraft)
                            {
                                // Always get a fresh event, in case it has been modified elsewhere.
                                EventEntry entry = each;

                                try { entry = GetElementByGoogleID(each.EventId, calendarService, feedUrl, each.Etag); }
                                catch (GDataNotModifiedException) { }

                                string   id             = GetDaytimerID(entry);
                                DateTime serverModified = entry.Edited.DateValue;
                                DateTime localModified  = DateTime.MinValue;
                                bool     exists         = false;

                                Appointment appt = new Appointment(false);

                                if (string.IsNullOrEmpty(id))
                                {
                                    appt.ID = IDGenerator.GenerateID();
                                    AddExtendedProperty(entry, DaytimerID, appt.ID);
                                }
                                else
                                {
                                    Appointment existing = AppointmentDatabase.GetAppointment(id);

                                    if (existing != null)
                                    {
                                        localModified = existing.LastModified;
                                        exists        = true;
                                        appt          = new Appointment(existing);
                                    }
                                    else
                                    {
                                        appt.ID = id;
                                    }
                                }

                                if (serverModified > localModified)
                                {
                                    // Prevent hangup where after first sync, all events would have
                                    // the same owner as the first synced account.
                                    if (!exists)
                                    {
                                        appt.Owner       = owner;
                                        appt.CalendarUrl = feedUrl;
                                    }

                                    if (entry.Times.Count > 0)
                                    {
                                        When when = entry.Times[0];

                                        appt.StartDate = when.StartTime;                                    //.ToLocalTime();
                                        appt.EndDate   = when.EndTime;                                      //.ToLocalTime();
                                        appt.AllDay    = when.AllDay;
                                    }

                                    if (entry.Reminders.Count > 0)
                                    {
                                        Reminder reminder = GetReminder(entry.Reminders,
                                                                        new Reminder.ReminderMethod[] { Reminder.ReminderMethod.alert, Reminder.ReminderMethod.all });                //entry.Reminders[0];

                                        if (reminder == null)
                                        {
                                            reminder = entry.Reminders[0];
                                        }

                                        appt.Reminder = reminder.Method == Reminder.ReminderMethod.none
                                                                                        ? TimeSpan.FromSeconds(-1)
                                                                                        : new TimeSpan(reminder.Days, reminder.Hours, reminder.Minutes, 0);
                                    }
                                    else
                                    {
                                        appt.Reminder = TimeSpan.FromSeconds(-1);
                                    }

                                    appt.Subject      = entry.Title.Text;
                                    appt.Location     = entry.Locations[0].ValueString;
                                    appt.ReadOnly     = entry.ReadOnly;
                                    appt.LastModified = serverModified;

                                    // Google only supports two "show as" values: Busy and Free.
                                    if (entry.EventTransparency.Value == EventEntry.Transparency.OPAQUE_VALUE)
                                    {
                                        appt.ShowAs = ShowAs.Busy;
                                    }
                                    else
                                    {
                                        if (appt.ShowAs == ShowAs.Busy)
                                        {
                                            appt.ShowAs = ShowAs.Free;
                                        }
                                        else
                                        {
                                            ExtendedProperty showas = GetExtendedProperty(entry, DaytimerShowAs);

                                            if (showas != null)
                                            {
                                                appt.ShowAs = (ShowAs)Enum.Parse(typeof(ShowAs), showas.Value, true);
                                            }
                                        }
                                    }

                                    if (entry.Recurrence != null)
                                    {
                                        appt.SetRecurrenceValues(entry.Recurrence.Value);
                                    }
                                    else
                                    {
                                        appt.IsRepeating = false;
                                    }

                                    if (entry.OriginalEvent != null)
                                    {
                                        EventEntry rEntry = GetElementByGoogleID(entry.OriginalEvent.IdOriginal, calendarService, feedUrl);

                                        string rID = GetDaytimerID(rEntry);

                                        if (string.IsNullOrEmpty(rID))
                                        {
                                            AddExtendedProperty(rEntry, DaytimerID, rID = IDGenerator.GenerateID());
                                        }

                                        appt.RepeatID = rID;
                                    }
                                    else
                                    {
                                        appt.RepeatID = null;
                                    }

                                    //ExtendedProperty details = GetExtendedProperty(entry, DaytimerDetails);
                                    //FlowDocument detailsDocument = null;

                                    //if (details != null)
                                    //	detailsDocument = FlowDocumentDeserialize(details.Value);

                                    if (!string.IsNullOrEmpty(entry.Content.Content))
                                    {
                                        // Since Google does not support text formatting,
                                        // don't change the document unless the text content
                                        // is different.
                                        if (appt.Details != entry.Content.Content)
                                        {
                                            // Edited through the Google UI or another application.
                                            //if (new TextRange(detailsDocument.ContentStart, detailsDocument.ContentEnd).Text != entry.Content.Content)
                                            appt.DetailsDocument = new FlowDocument(new Paragraph(new Run(entry.Content.Content)));

                                            //// Edited through another Daytimer application.
                                            //else
                                            //	appt.DetailsDocument = detailsDocument;
                                        }
                                    }
                                    else
                                    {
                                        //if (detailsDocument != null && string.IsNullOrEmpty(new TextRange(detailsDocument.ContentStart, detailsDocument.ContentEnd).Text))
                                        //	appt.DetailsDocument = detailsDocument;
                                        //else
                                        appt.DetailsDocument = new FlowDocument();
                                    }

                                    //
                                    // Custom attributes
                                    //
                                    ExtendedProperty category = GetExtendedProperty(entry, DaytimerCategory);
                                    ExtendedProperty priority = GetExtendedProperty(entry, DaytimerPriority);

                                    if (category != null)
                                    {
                                        appt.CategoryID = category.Value;
                                    }

                                    if (priority != null)
                                    {
                                        appt.Priority = (Priority)Enum.Parse(typeof(Priority), priority.Value, true);
                                    }


                                    if (exists)
                                    {
                                        AppointmentDatabase.UpdateAppointment(appt, false);
                                    }
                                    else
                                    {
                                        AppointmentDatabase.Add(appt, false);
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (each.OriginalEvent != null)
                            {
                                EventEntry rEntry = GetElementByGoogleID(each.OriginalEvent.IdOriginal, calendarService, feedUrl);

                                if (rEntry != null)
                                {
                                    string rID = GetDaytimerID(rEntry);

                                    if (string.IsNullOrEmpty(rID))
                                    {
                                        AddExtendedProperty(rEntry, DaytimerID, rID = IDGenerator.GenerateID());
                                    }

                                    Appointment appt = AppointmentDatabase.GetAppointment(rID);

                                    if (appt == null)
                                    {
                                        appt             = new Appointment(false);
                                        appt.ID          = rID;
                                        appt.Owner       = owner;
                                        appt.CalendarUrl = feedUrl;
                                    }
                                    else if (appt.Owner != owner || (appt.CalendarUrl != "" && appt.CalendarUrl != feedUrl))
                                    {
                                        break;
                                    }

                                    DateTime[] skip = appt.Recurrence.Skip;

                                    if (skip == null)
                                    {
                                        skip = new DateTime[] { each.Times[0].StartTime.Date }
                                    }
                                    ;
                                    else
                                    {
                                        if (Array.IndexOf(skip, each.Times[0].StartTime.Date) == -1)
                                        {
                                            Array.Resize <DateTime>(ref skip, skip.Length + 1);
                                            skip[skip.Length - 1] = each.Times[0].StartTime.Date;
                                        }
                                    }

                                    appt.Recurrence.Skip = skip;
                                    appt.IsRepeating     = true;
                                    AppointmentDatabase.UpdateAppointment(appt, false);


                                    //if (!string.IsNullOrEmpty(rID))
                                    //{
                                    //// If the appointment is null, it will be synced later; we don't have to worry about
                                    //// reading the skip dates now.
                                    //if (appt != null)
                                    //{
                                    //	DateTime[] skip = appt.RepeatSkip;

                                    //	if (skip == null)
                                    //		skip = new DateTime[] { each.Times[0].StartTime.Date };
                                    //	else
                                    //	{
                                    //		if (Array.IndexOf(skip, each.Times[0].StartTime.Date) == -1)
                                    //		{
                                    //			Array.Resize<DateTime>(ref skip, skip.Length + 1);
                                    //			skip[skip.Length - 1] = each.Times[0].StartTime.Date;
                                    //		}
                                    //	}

                                    //	appt.RepeatSkip = skip;
                                    //	AppointmentDatabase.UpdateAppointment(appt, false);
                                    //}
                                    //}
                                }
                                else
                                {
                                    string id = GetDaytimerID(each);

                                    if (id != null)
                                    {
                                        Appointment del = AppointmentDatabase.GetAppointment(id);

                                        if (del != null && del.Owner == owner && (del.CalendarUrl == feedUrl || del.CalendarUrl == ""))
                                        {
                                            AppointmentDatabase.Delete(id, false);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                string id = GetDaytimerID(each);

                                if (id != null)
                                {
                                    Appointment del = AppointmentDatabase.GetAppointment(id);

                                    if (del != null &&
                                        del.Owner == owner && (del.CalendarUrl == feedUrl || del.CalendarUrl == ""))
                                    {
                                        AppointmentDatabase.Delete(id, false);
                                    }
                                }
                            }
                        }

                        break;
                    }
                    catch
                    {
                        if (i == MaxTries - 1)
                        {
                            throw;
                        }

                        Thread.Sleep(AttemptDelay);
                    }

                    token.ThrowIfCancellationRequested();
                }
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Downloads data from server, and uploads local data to server for all linked Google accounts.
        /// </summary>
        private void GlobalResync(CancellationToken token)
        {
            DateTime lastSync = Settings.LastSuccessfulSync;

            try
            {
                GoogleAccount[] accounts = GoogleAccounts.AllAccounts();

                if (accounts == null || accounts.Length == 0)
                {
                    Done = true;
                    return;
                }

                ThrowIfNetworkUnavailable();

                // Lock the last sync in now; any events created during the
                // sync process will be ignored, and will be handled by the
                // next sync.
                Settings.LastSuccessfulSync = DateTime.UtcNow;

                SyncObject[] upload = SyncDatabase.AllSyncObjects();

                token.ThrowIfCancellationRequested();

                //
                // Calendars
                //
                Status = "Downloading calendar list";

                int calendars = SyncCalendars(accounts, token);
                _total    = calendars * 3 + 2;
                _progress = 1;
                RaiseEvent(ProgressChangedEvent);

                token.ThrowIfCancellationRequested();

                //
                // Events
                //
                foreach (GoogleAccount gAccount in accounts)
                {
                    string email = gAccount.Email;

                    foreach (string feedUrl in gAccount.LinkedCalendars)
                    {
                        //
                        // Update new account
                        //
                        if (SyncDatabase.GetSyncObject(email) != null)
                        {
                            Status = "Syncing " + email;

                            CalendarHelper.MergeCalendar(email, gAccount.Password, feedUrl, token);
                            SyncDatabase.Delete(email);

                            token.ThrowIfCancellationRequested();

                            _progress += 3;
                            RaiseEvent(ProgressChangedEvent);
                        }

                        //
                        // Update existing account
                        //
                        else
                        {
                            CalendarService calendarService = CalendarHelper.GetService(GlobalData.GoogleDataAppName,
                                                                                        email, gAccount.Password);

                            Status = "Uploading local calendar";

                            foreach (SyncObject each in upload)
                            {
                                switch (each.SyncType)
                                {
                                case SyncType.Create:
                                case SyncType.Modify:
                                {
                                    if (each.OldUrl != "")
                                    {
                                        // We don't know which account owned this calendar; try to delete it
                                        // from every account.
                                        try
                                        {
                                            IEnumerable <EventEntry> entries = CalendarHelper.GetElementsByDaytimerID(
                                                each.ReferenceID, calendarService, each.OldUrl,
                                                token);

                                            if (entries != null)
                                            {
                                                foreach (EventEntry entry in entries)
                                                {
                                                    entry.Delete();
                                                }
                                            }
                                        }
                                        catch { }
                                    }

                                    Appointment appt = AppointmentDatabase.GetAppointment(each.ReferenceID);

                                    //if (appt != null && appt.Sync && (appt.Owner == "" || appt.Owner == email))
                                    //	CalendarHelper.AddEvent(calendarService, feedUrl, appt);

                                    // Uncomment the following method after UI is implemented
                                    // which allows user to select where to upload event.

                                    if (appt != null && appt.Sync && appt.Owner == email)                                                    // && (appt.Owner == "" || appt.Owner == email))
                                    {
                                        CalendarHelper.AddEvent(calendarService,
                                                                appt.CalendarUrl != "" ? appt.CalendarUrl : feedUrl, appt,
                                                                token);
                                    }
                                }
                                break;

                                case SyncType.Delete:
                                {
                                    IEnumerable <EventEntry> entries = CalendarHelper.GetElementsByDaytimerID(
                                        each.ReferenceID, calendarService, each.Url != "" ? each.Url : feedUrl,
                                        token);

                                    if (entries != null)
                                    {
                                        foreach (EventEntry entry in entries)
                                        {
                                            entry.Delete();
                                        }
                                    }
                                }
                                break;

                                default:
                                    break;
                                }
                            }

                            token.ThrowIfCancellationRequested();

                            _progress++;
                            RaiseEvent(ProgressChangedEvent);

                            Status = "Downloading " + email;

                            IEnumerable <EventEntry> download = CalendarHelper.GetAllEventsModifiedSince(calendarService, feedUrl, lastSync, token);

                            token.ThrowIfCancellationRequested();

                            _progress++;
                            RaiseEvent(ProgressChangedEvent);

                            CalendarHelper.DownloadMergeCalendar(download, email, calendarService, feedUrl, token);

                            token.ThrowIfCancellationRequested();

                            _progress++;
                            RaiseEvent(ProgressChangedEvent);
                        }
                    }
                }

                Status = "Cleaning up";

                // Clear sync queue
                foreach (SyncObject each in upload)
                {
                    SyncDatabase.Delete(each);
                }

                _progress++;
                RaiseEvent(ProgressChangedEvent);
            }
            catch (Exception exc)
            {
                _error = exc;
                Settings.LastSuccessfulSync = lastSync;
            }
            finally
            {
                ReminderQueue.Populate();
                Done = true;
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Show an alert based on a reminder.
        /// </summary>
        /// <param name="reminder"></param>
        private static void DisplayAlert(Reminder reminder)
        {
            if (!IsOpen(reminder) && !IsQueued(reminder))
            {
                //Thread alertThread = new Thread(() =>
                //{
                Application.Current.Dispatcher.BeginInvoke(() =>
                {
                    Toast alert;
                    string sound = Settings.AlertSound;

                    if (reminder.ReminderType == ReminderType.Appointment)
                    {
                        Appointment appt = AppointmentDatabase.GetAppointment(reminder.ID);

                        string timeString = "";                        // reminder.StartTime.ToShortDateString();

                        //timeString += " » ";

                        if (appt.AllDay)
                        {
                            if ((reminder.EventStartDate.Value - reminder.EventEndDate.Value).TotalDays > 1)
                            {
                                timeString = reminder.EventStartDate.Value.Date.ToShortDateString() + " - "
                                             + reminder.EventEndDate.Value.Date.ToShortDateString();
                            }
                            else
                            {
                                timeString = reminder.EventStartDate.Value.Date.ToShortDateString();
                            }

                            timeString += " » All Day";
                        }
                        else
                        {
                            if ((reminder.EventStartDate.Value.Date != reminder.EventEndDate.Value.Date))
                            {
                                timeString = reminder.EventStartDate.Value.ToShortDateString() + " "
                                             + RandomFunctions.FormatTime(reminder.EventStartDate.Value.TimeOfDay)
                                             + " - " + reminder.EventEndDate.Value.ToShortDateString() + " "
                                             + RandomFunctions.FormatTime(reminder.EventEndDate.Value.TimeOfDay);
                            }
                            else
                            {
                                timeString  = reminder.EventStartDate.Value.Date.ToShortDateString();
                                timeString += " » " +
                                              RandomFunctions.FormatTime(appt.StartDate.TimeOfDay) + " - "
                                              + RandomFunctions.FormatTime(appt.EndDate.TimeOfDay);
                            }
                        }

                        alert = new Toast(
                            !string.IsNullOrEmpty(appt.Subject) ? appt.Subject : "(No subject)",
                            appt.Location,
                            timeString,
                            new BitmapImage(new Uri("pack://*****:*****@"Resources/Media/" + sound, UriKind.Relative),
                            ToastDuration.Long,
                            Settings.UnmuteSpeakers);
                    }
                    else
                    {
                        UserTask task = TaskDatabase.GetTask(reminder.ID);
                        alert         = new Toast(
                            !string.IsNullOrEmpty(task.Subject) ? task.Subject : "(No subject)",
                            task.Priority.ToString(),
                            task.DueDate.HasValue ? task.DueDate.Value.ToShortDateString() : "No due date",
                            new BitmapImage(new Uri("pack://*****:*****@"Resources/Media/" + sound, UriKind.Relative),
                            ToastDuration.Long,
                            Settings.UnmuteSpeakers);
                    }

                    alert.Tag     = reminder;
                    alert.Closed += alert_Closed;
                    alert.Open();
                });
                //});

                //alertThread.SetApartmentState(ApartmentState.STA);
                //alertThread.IsBackground = true;
                //alertThread.Start();
            }
        }