예제 #1
0
        public static EKEvent[] FetchEvents(DateTime startDate, DateTime endDate)
        {
            // Create the predicate. Pass it the default calendar.
            //Util.WriteLine ("Getting Calendars");
            EKEventStore store = new EKEventStore();
//			store.RequestAccess (EKEntityType.Event, (bool granted, NSError e) => {
//				if (granted)
//				{
//#if DEBUG
//					Console.WriteLine("Access Granted!");
//#endif
//					//Do add events calendars and any calendar stuff here
//				}
//				else
//					new UIAlertView ( "Access Denied", "User Denied Access to Calendar Data", null, "ok", null).Show ();
//			}
//			);
            var calendarArray = store.Calendars;
            //Util.WriteLine ("Predicate");
            //Convert to NSDate
            NSDate      nstartDate = startDate.DateTimeToNSDate();
            NSDate      nendDate   = endDate.DateTimeToNSDate();
            NSPredicate predicate  = store.PredicateForEvents(nstartDate, nendDate, calendarArray);

            //Util.WriteLine ("Fetching Events");
            // Fetch all events that match the predicate.
            var eventsArray = store.EventsMatching(predicate);

            //Util.WriteLine ("Returning results");
            if (eventsArray == null)
            {
                eventsArray = new List <EKEvent> ().ToArray();
            }
            return(eventsArray);
        }
예제 #2
0
        /// <summary>
        /// Gets event data in a specific date range
        /// </summary>
        public static object[] GetEventsFromTo(DateTime fromDate, DateTime toDate)
        {
            Debug.Log("in GetEventsFromTo, output of calendar: " + calendar);
            DateTime startDate = fromDate;
            DateTime endDate   = toDate;

            object[] calenderArray = new object[1];
            calenderArray[0] = calendar;
            NSPredicate predicate = eventStore.PredicateForEvents(startDate, endDate, calenderArray);

            object[] eventObjs = eventStore.EventsMatchingPredicate(predicate);
            if (eventObjs != null)
            {
                eventStore.SaveCalendar(calendar, true, null);
                eventStore.Commit(null);
            }
            return(eventObjs);
        }
예제 #3
0
        public static EKEvent getEvent(CalendarDayEventView theEventView)
        {
            EKEventStore store         = MyEventStore;
            var          calendarArray = store.Calendars;
            //Util.WriteLine ("Predicate");
            //var newNSDate = (NSDate)theEventView.endDate;
            //Console.WriteLine ("Date is: {0} {1} {2}", NSDate.Now.ToString (), ((NSDate) DateTime.Now).ToString (), DateTime.Now);
            NSPredicate predicate = store.PredicateForEvents(theEventView.nsStartDate, theEventView.nsEndDate, calendarArray);

            //Util.WriteLine ("Fetching Events");
            // Fetch all events that match the predicate.
            return(store.EventsMatching(predicate).Where(x => x.EventIdentifier == theEventView.eventIdentifier).FirstOrDefault());
        }
예제 #4
0
        public void AddEvent(string Titulo, string Lugar, DateTime Inicio, DateTime Termina, string Descripcion)
        {
            try
            {
                EKEventStore evStore = new EKEventStore();
                evStore.RequestAccess(EKEntityType.Event, (bool granted, NSError e) => {
                    if (!granted)
                    {
                        new UIAlertView("Acceso denegado", "El usuario no permite acceso al calendario", null, "ok", null).Show();
                    }
                });
                EKCalendar  calendar    = evStore.DefaultCalendarForNewEvents;
                NSPredicate evPredicate = evStore.PredicateForEvents(Inicio, Termina, evStore.GetCalendars(EKEntityType.Event));
                bool        encontrado  = false;

                evStore.EnumerateEvents(evPredicate, delegate(EKEvent calEvent, ref bool stop) {
                    if (calEvent.Title == Titulo)
                    {
                        encontrado = true;
                    }
                });
                if (encontrado)
                {
                    new UIAlertView("Evento", "El evento ya existe en el calendario", null, "ok", null).Show();
                }
                else
                {
                    EKEvent newEvent = EKEvent.FromStore(evStore);
                    newEvent.Title     = Titulo;
                    newEvent.Notes     = Descripcion;
                    newEvent.Calendar  = calendar;
                    newEvent.StartDate = Inicio;
                    newEvent.EndDate   = Termina;
                    newEvent.Location  = Lugar;
                    var error = new NSError(new NSString(""), 0);
                    evStore.SaveEvent(newEvent, EKSpan.ThisEvent, out error);
                    if (error.LocalizedDescription != "")
                    {
                        new UIAlertView("Evento", "Hubo un problema al agregar el evento " + error.LocalizedDescription, null, "ok", null).Show();
                    }
                    else
                    {
                        new UIAlertView("Evento", "El evento se agregó a su calendario", null, "ok", null).Show();
                    }
                }
            }
            catch (Exception) {
                new UIAlertView("Evento", "Hubo un problema al agregar el evento", null, "ok", null).Show();
            }
        }
예제 #5
0
        public void AddEvent(string Titulo, string Lugar, DateTime Inicio, DateTime Termina, string Descripcion)
        {
            try
            {
                EKEventStore evStore = new EKEventStore();
                evStore.RequestAccess(EKEntityType.Event, (bool granted, NSError e) => {
                    if (!granted)
                        new UIAlertView("Acceso denegado", "El usuario no permite acceso al calendario", null, "ok", null).Show();
                });
                EKCalendar calendar = evStore.DefaultCalendarForNewEvents;
                NSPredicate evPredicate = evStore.PredicateForEvents(Inicio, Termina, evStore.GetCalendars(EKEntityType.Event));
                bool encontrado = false;

                evStore.EnumerateEvents(evPredicate, delegate(EKEvent calEvent, ref bool stop) {
                    if (calEvent.Title == Titulo)
                        encontrado = true;
                });
                if (encontrado)
                {
                    new UIAlertView("Evento", "El evento ya existe en el calendario", null, "ok", null).Show();
                }
                else
                {
                    EKEvent newEvent = EKEvent.FromStore(evStore);
                    newEvent.Title = Titulo;
                    newEvent.Notes = Descripcion;
                    newEvent.Calendar = calendar;
                    newEvent.StartDate = Inicio;
                    newEvent.EndDate = Termina;
                    newEvent.Location = Lugar;
                    var error = new NSError(new NSString(""), 0);
                    evStore.SaveEvent(newEvent, EKSpan.ThisEvent, out error);
                    if(error.LocalizedDescription!="")
                        new UIAlertView("Evento", "Hubo un problema al agregar el evento " + error.LocalizedDescription, null, "ok", null).Show();
                    else
                        new UIAlertView("Evento", "El evento se agregó a su calendario", null, "ok", null).Show();
                }
            }
            catch (Exception) {
                new UIAlertView("Evento", "Hubo un problema al agregar el evento", null, "ok", null).Show();
            }
            
        }
예제 #6
0
        /// <summary>
        /// Gets all events for a calendar within the specified time range.
        /// </summary>
        /// <param name="calendar">Calendar containing events</param>
        /// <param name="start">Start of event range</param>
        /// <param name="end">End of event range</param>
        /// <returns>Calendar events</returns>
        /// <exception cref="System.ArgumentException">Calendar does not exist on device</exception>
        /// <exception cref="System.UnauthorizedAccessException">Calendar access denied</exception>
        /// <exception cref="Calendars.Plugin.Abstractions.PlatformException">Unexpected platform-specific error</exception>
        public async Task <IList <CalendarEvent> > GetEventsAsync(Calendar calendar, DateTime start, DateTime end)
        {
            await RequestCalendarAccess().ConfigureAwait(false);

            var deviceCalendar = _eventStore.GetCalendar(calendar.ExternalID);

            if (deviceCalendar == null)
            {
                throw new ArgumentException("Specified calendar not found on device");
            }

            var query  = _eventStore.PredicateForEvents(start.ToNSDate(), end.ToNSDate(), new EKCalendar[] { deviceCalendar });
            var events = await Task.Run(() =>
            {
                var iosEvents = _eventStore.EventsMatching(query);
                return(iosEvents == null ? new List <CalendarEvent>() : iosEvents.Select(e => e.ToCalendarEvent()).ToList());
            }).ConfigureAwait(false);

            return(events);
        }
예제 #7
0
        protected override List <CalendarDatum> GetCalendarEventsAsync()
        {
            List <CalendarDatum> datums = new List <CalendarDatum>();
            EKEventStore         store  = new EKEventStore();

            EKCalendar[] calendars = store.GetCalendars(EKEntityType.Event);

            NSDate last = (NSDate)LastPollTime;
            NSDate now  = (NSDate)DateTime.Now;

            NSPredicate predicate = store.PredicateForEvents(last, now, calendars);

            EKEvent[] items = store.EventsMatching(predicate);

            foreach (EKEvent item in items)
            {
                CalendarDatum datum = new CalendarDatum(item.EventIdentifier, item.Title, (DateTime)item.StartDate, (DateTime)item.EndDate, ((DateTime)item.EndDate - (DateTime)item.StartDate).TotalMilliseconds, item.Description, item.Location, item.Organizer?.Name, item.Organizer == null || item.Organizer?.IsCurrentUser == true, DateTimeOffset.UtcNow);

                datums.Add(datum);
            }

            return(datums);
        }
예제 #8
0
        /// <summary>
        /// This method retrieves all the events for the past week via a query and displays them
        /// on the EventList Screen.
        /// </summary>
        protected void GetEventsViaQuery(DateTime startDate, DateTime endDate)
        {
            List<CalendarEntry> eventsList = new List<CalendarEntry>();
            try {
                EKEventStore store = new EKEventStore();
                EKCalendar calendar = store.DefaultCalendarForNewEvents;

                // Query the event
                if (calendar != null)
                {
                    // Searches for every event in the range of given dates
                    NSPredicate predicate = store.PredicateForEvents(IPhoneUtils.DateTimeToNSDate(startDate),IPhoneUtils.DateTimeToNSDate(endDate),new EKCalendar[] {calendar});
                    store.EnumerateEvents(predicate, delegate(EKEvent currentEvent, ref bool stop)
                                          {
                        // Perform your check for an event type
                        CalendarEntry entry = new CalendarEntry();
                        entry.Uid = currentEvent.EventIdentifier;
                        entry.Title = currentEvent.Title;
                        entry.Notes = currentEvent.Notes;
                        entry.Location = currentEvent.Location;
                        entry.IsAllDayEvent = currentEvent.AllDay;
                        entry.StartDate = IPhoneUtils.NSDateToDateTime(currentEvent.StartDate);
                        entry.EndDate = IPhoneUtils.NSDateToDateTime(currentEvent.EndDate);

                        try {

                            // TODO: locate how to translate this features
                            // entry.Type (birthday, exchange, etc)
                            //calendarEvent.  = entry.IsEditable

                            // Attendees
                            if(currentEvent.Attendees != null && currentEvent.Attendees.Length>0) {
                                int attendeesNum = currentEvent.Attendees.Length;
                                entry.Attendees = new CalendarAttendee[attendeesNum];
                                int index = 0;
                                foreach(EKParticipant participant in currentEvent.Attendees) {
                                    CalendarAttendee attendee = new CalendarAttendee();
                                    attendee.Name = participant.Name;
                                    attendee.Address = participant.Url.AbsoluteString;
                                    if(participant.ParticipantStatus == EKParticipantStatus.Unknown || participant.ParticipantStatus == EKParticipantStatus.Pending) {
                                        attendee.Status = AttendeeStatus.NeedsAction;
                                    }
                                    entry.Attendees[index] = attendee;
                                    index++;
                                }
                            }

                            // Alarms
                            if(currentEvent.HasAlarms && currentEvent.Alarms != null && currentEvent.Alarms.Length >0) {
                                int alarmsNum = currentEvent.Alarms.Length;
                                entry.Alarms = new CalendarAlarm[alarmsNum];
                                int index = 0;
                                foreach(EKAlarm alarm in currentEvent.Alarms) {
                                    CalendarAlarm eventAlarm = new CalendarAlarm();
                                    eventAlarm.Trigger = IPhoneUtils.NSDateToDateTime(alarm.AbsoluteDate);
                                    // TODO: how to manage "action", "sound" and "emailaddress"
                                    entry.Alarms[index] = eventAlarm;
                                    index++;
                                }
                            }

                            // Recurrence Rules (pick only the first one)
                            if(currentEvent.HasRecurrenceRules && currentEvent.RecurrenceRules != null && currentEvent.RecurrenceRules.Length >0) {
                                entry.IsRecurrentEvent = true;
                                EKRecurrenceRule rule = currentEvent.RecurrenceRules[0];
                                if(rule != null) {
                                    entry.Recurrence = new CalendarRecurrence();
                                    if(rule.Frequency == EKRecurrenceFrequency.Weekly) {
                                        entry.Recurrence.Type = RecurrenceType.Weekly;
                                    } else if(rule.Frequency == EKRecurrenceFrequency.Monthly) {
                                        entry.Recurrence.Type = RecurrenceType.Montly;
                                    } else if(rule.Frequency == EKRecurrenceFrequency.Yearly) {
                                        entry.Recurrence.Type = RecurrenceType.Yearly;
                                    }
                                    if(rule.RecurrenceEnd != null) {
                                        entry.Recurrence.EndDate = IPhoneUtils.NSDateToDateTime(rule.RecurrenceEnd.EndDate);
                                        entry.Recurrence.Interval = (int)rule.Interval;
                                        entry.RecurrenceNumber = rule.RecurrenceEnd.OccurrenceCount;
                                    }
                                }
                            }

                        } catch (Exception ex) {
                                SystemLogger.Log(SystemLogger.Module.PLATFORM, "Unhandled exception while getting calendar entry information (event_id=" + entry.Uid +"). Exception message: " + ex.Message);
                        }

                        eventsList.Add(entry);
                    });

                }
            } catch (Exception ex) {
                SystemLogger.Log(SystemLogger.Module.PLATFORM, "Unhandled exception while getting calendar entries. Exception message: " + ex.Message);
            }

            SystemLogger.Log(SystemLogger.Module.PLATFORM, "eventsList: " + eventsList.Count);
            UIApplication.SharedApplication.InvokeOnMainThread (delegate {
                IPhoneUtils.GetInstance().FireUnityJavascriptEvent("Appverse.Pim.onListCalendarEntriesEnd", eventsList);
            });
        }
예제 #9
0
파일: Util.cs 프로젝트: Clancey/UICalendar
        public static EKEvent[] FetchEvents(DateTime startDate, DateTime endDate)
        {
            // Create the predicate. Pass it the default calendar.
            //Util.WriteLine ("Getting Calendars");
            EKEventStore store = new EKEventStore ();
            store.RequestAccess (EKEntityType.Event, (bool granted, NSError e) => {
                if (granted)
                {
            #if DEBUG
                    Console.WriteLine("Access Granted!");
            #endif
                    //Do add events calendars and any calendar stuff here
                }
                else
                    new UIAlertView ( "Access Denied", "User Denied Access to Calendar Data", null, "ok", null).Show ();
            }
            );
            var calendarArray = store.Calendars;
            //Util.WriteLine ("Predicate");
            //Convert to NSDate
            NSDate nstartDate = startDate.DateTimeToNSDate();
            NSDate nendDate = endDate.DateTimeToNSDate();
            NSPredicate predicate = store.PredicateForEvents (nstartDate, nendDate, calendarArray);

            //Util.WriteLine ("Fetching Events");
            // Fetch all events that match the predicate.
            var eventsArray = store.EventsMatching (predicate);
            //Util.WriteLine ("Returning results");
            if (eventsArray == null) {
                eventsArray = new List<EKEvent> ().ToArray ();
            }
            return eventsArray;
        }
예제 #10
0
        /// <summary>
        /// This method retrieves all the events for the past week via a query and displays them
        /// on the EventList Screen.
        /// </summary>
        protected void GetEventsViaQuery(DateTime startDate, DateTime endDate)
        {
            List<CalendarEntry> eventsList = new List<CalendarEntry>();
            EKEventStore store = new EKEventStore();
            EKCalendar calendar = store.DefaultCalendarForNewEvents;

            // Query the event
            if (calendar != null)
            {
                // Searches for every event in the range of given dates
                NSPredicate predicate = store.PredicateForEvents(startDate,endDate,new EKCalendar[] {calendar});
                store.EnumerateEvents(predicate, delegate(EKEvent currentEvent, ref bool stop)
                                      {
                    // Perform your check for an event type
                    CalendarEntry entry = new CalendarEntry();
                    entry.Uid = currentEvent.EventIdentifier;
                    entry.Title = currentEvent.Title;
                    entry.Notes = currentEvent.Notes;
                    entry.Location = currentEvent.Location;
                    entry.IsAllDayEvent = currentEvent.AllDay;
                    entry.StartDate = currentEvent.StartDate;
                    entry.EndDate = currentEvent.EndDate;

                    // TODO: locate how to translate this features
                    // entry.Type (birthday, exchange, etc)
                    //calendarEvent.  = entry.IsEditable

                    // Attendees
                    if(currentEvent.Attendees != null && currentEvent.Attendees.Length>0) {
                        int attendeesNum = currentEvent.Attendees.Length;
                        entry.Attendees = new CalendarAttendee[attendeesNum];
                        int index = 0;
                        foreach(EKParticipant participant in currentEvent.Attendees) {
                            CalendarAttendee attendee = new CalendarAttendee();
                            attendee.Name = participant.Name;
                            attendee.Address = participant.Url.AbsoluteString;
                            if(participant.ParticipantStatus == EKParticipantStatus.Unknown || participant.ParticipantStatus == EKParticipantStatus.Pending) {
                                attendee.Status = AttendeeStatus.NeedsAction;
                            }
                            entry.Attendees[index] = attendee;
                            index++;
                        }
                    }

                    // Alarms
                    if(currentEvent.HasAlarms && currentEvent.Alarms != null && currentEvent.Alarms.Length >0) {
                        int alarmsNum = currentEvent.Alarms.Length;
                        entry.Alarms = new CalendarAlarm[alarmsNum];
                        int index = 0;
                        foreach(EKAlarm alarm in currentEvent.Alarms) {
                            CalendarAlarm eventAlarm = new CalendarAlarm();
                            eventAlarm.Trigger = alarm.AbsoluteDate;
                            // TODO: how to manage "action", "sound" and "emailaddress"
                            entry.Alarms[index] = eventAlarm;
                            index++;
                        }
                    }

                    // Recurrence Rules (pick only the first one)
                    if(currentEvent.HasRecurrenceRules && currentEvent.RecurrenceRules != null && currentEvent.RecurrenceRules.Length >0) {
                        entry.IsRecurrentEvent = true;
                        EKRecurrenceRule rule = currentEvent.RecurrenceRules[0];
                        if(rule != null) {
                            entry.Recurrence = new CalendarRecurrence();
                            if(rule.Frequency == EKRecurrenceFrequency.Weekly) {
                                entry.Recurrence.Type = RecurrenceType.Weekly;
                            } else if(rule.Frequency == EKRecurrenceFrequency.Monthly) {
                                entry.Recurrence.Type = RecurrenceType.Montly;
                            } else if(rule.Frequency == EKRecurrenceFrequency.Yearly) {
                                entry.Recurrence.Type = RecurrenceType.Yearly;
                            }
                            if(rule.RecurrenceEnd != null) {
                                entry.Recurrence.EndDate = rule.RecurrenceEnd.EndDate;
                                entry.Recurrence.Interval = rule.Interval;
                                entry.RecurrenceNumber = rule.RecurrenceEnd.OccurrenceCount;
                            }
                        }
                    }

                    eventsList.Add(entry);
                });

            }

            // TODO :: this API could no longer be invoked in this way.
            // the list of entries must be queried after checking access --> so, process has to send data via callback

            // return eventsList.ToArray();
        }
예제 #11
0
        public async void AddEventToCalender(object sender, EventArgs e)
        {
            try
            {
                var store = new EKEventStore();
                if (EKEventStore.GetAuthorizationStatus(EKEntityType.Reminder) == EKAuthorizationStatus.Authorized)
                {
                    if (EKEventStore.GetAuthorizationStatus(EKEntityType.Event) == EKAuthorizationStatus.Authorized)
                    {
                        NSDate           startDate = ConvertDateTimeToNSDate(BaseFunctions.GetDateTimeFull(App.reminderEvent.eventStartDate + " " + App.reminderEvent.eventStartTime));
                        NSDate           endDate   = ConvertDateTimeToNSDate(BaseFunctions.GetDateTimeFull(App.reminderEvent.eventEndDate + " " + App.reminderEvent.eventEndTime));
                        NSPredicate      query     = store.PredicateForEvents(startDate, endDate, null);
                        EKCalendarItem[] events    = store.EventsMatching(query);
                        bool             exists    = false;
                        for (int i = 0; i < events.Length; i++)
                        {
                            if (events[i].Title == App.reminderEvent.eventName)
                            {
                                exists = true;
                            }
                        }
                        if (!exists)
                        {
                            EKEvent eEvent = EKEvent.FromStore(store);
                            eEvent.AddAlarm(EKAlarm.FromDate(ConvertDateTimeToNSDate(BaseFunctions.GetDateTimeFull(App.reminderEvent.eventStartDate + " " + App.reminderEvent.eventStartTime))));
                            eEvent.StartDate = startDate;
                            eEvent.EndDate   = endDate;
                            eEvent.Title     = App.reminderEvent.eventName;
                            eEvent.TimeZone  = new NSTimeZone("UTC");
                            eEvent.Location  = App.reminderEvent.eventAddress;
                            eEvent.Notes     = App.reminderEvent.eventDescription;
                            eEvent.Calendar  = store.DefaultCalendarForNewEvents;
                            NSError eventError;
                            store.SaveEvent(eEvent, EKSpan.ThisEvent, out eventError);

                            EKReminder reminder = EKReminder.Create(store);
                            reminder.Title = App.reminderEvent.eventName;
                            reminder.AddAlarm(EKAlarm.FromDate(ConvertDateTimeToNSDate(BaseFunctions.GetDateTimeFull(App.reminderEvent.eventStartDate + " " + App.reminderEvent.eventStartTime))));
                            reminder.TimeZone = new NSTimeZone("UTC");
                            reminder.Calendar = store.DefaultCalendarForNewEvents;
                            await App.Current.MainPage.DisplayAlert("Alert", "This event is added to your calender", "Ok");
                        }
                        else
                        {
                            await App.Current.MainPage.DisplayAlert("Alert", "This event is already added to your calender", "Ok");
                        }
                    }
                    else
                    {
                        store.RequestAccess(EKEntityType.Event, StoreAcceptRequest);
                    }
                }
                else
                {
                    store.RequestAccess(EKEntityType.Reminder, StoreAcceptRequest);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
        }
예제 #12
0
파일: Util.cs 프로젝트: thiblege/UICalendar
        public static EKEvent[] FetchEvents(DateTime startDate, DateTime endDate)
        {
            // Create the predicate. Pass it the default calendar.
            //Util.WriteLine ("Getting Calendars");
            EKEventStore store = new EKEventStore ();
            var calendarArray = store.Calendars;
            //Util.WriteLine ("Predicate");
            //Convert to NSDate
            NSDate nstartDate = Util.DateTimeToNSDate (startDate);
            NSDate nendDate = Util.DateTimeToNSDate (endDate);
            NSPredicate predicate = store.PredicateForEvents (nstartDate, nendDate, calendarArray);

            //Util.WriteLine ("Fetching Events");
            // Fetch all events that match the predicate.
            var eventsArray = store.EventsMatching (predicate);
            //Util.WriteLine ("Returning results");
            if (eventsArray == null) {
                eventsArray = new List<EKEvent> ().ToArray ();
            }
            return eventsArray;
        }