示例#1
0
        static EKCalendar CreateNewCalendar()
        {
            NSError    err;
            EKCalendar cal = EKCalendar.Create(EKEntityType.Event, EventStore);

            cal.Title = "Evènements Epitech";
            foreach (EKSource s in EventStore.Sources)
            {
                if (s.SourceType == EKSourceType.CalDav)
                {
                    cal.Source = s;
                    break;
                }
            }
            if (cal.Source == null)
            {
                foreach (EKSource s in EventStore.Sources)
                {
                    if (s.SourceType == EKSourceType.Local)
                    {
                        cal.Source = s;
                        break;
                    }
                }
            }
            bool didwell = EventStore.SaveCalendar(cal, true, out err);

            if (!didwell)
            {
                throw new Exception("SaveCalendar failed");
            }
            NSUserDefaults.StandardUserDefaults.SetString(cal.CalendarIdentifier, CalendarIDKey);
            NSUserDefaults.StandardUserDefaults.Synchronize();
            return(cal);
        }
示例#2
0
        /// <summary>
        /// Tries to create a new calendar with the specified source/name/color.
        /// May fail depending on source.
        /// </summary>
        /// <remarks>
        /// This is only intended as a helper method for CreateEKCalendar,
        /// not to be called independently.
        /// </remarks>
        /// <returns>The created native calendar, or null on failure</returns>
        /// <param name="source">Calendar source (e.g. iCloud vs local vs gmail)</param>
        /// <param name="calendarName">Calendar name.</param>
        /// <param name="color">Calendar color.</param>
        private EKCalendar SaveEKCalendar(EKSource source, string calendarName, string color = null)
        {
            var calendar = EKCalendar.Create(EKEntityType.Event, _eventStore);

            // Setup calendar to be inserted
            //
            calendar.Title = calendarName;

            if (!string.IsNullOrEmpty(color))
            {
                calendar.CGColor = ColorConversion.ToCGColor(color);
            }

            calendar.Source = source;

            NSError error = null;

            if (_eventStore.SaveCalendar(calendar, true, out error))
            {
                Console.WriteLine($"Successfully saved calendar with source {source.Title}");

                // TODO: Should we try calling GetCalendars to make sure that
                //       the calendar isn't hidden??
                //
                return(calendar);
            }
            else
            {
                Console.WriteLine($"Tried and failed to save calendar with source {source.Title}");
            }

            _eventStore.Reset();

            return(null);
        }
示例#3
0
        EKCalendar SaveEKCalendar(EKSource source, string calendarName, string color = null)
        {
            var calendar = EKCalendar.Create(EKEntityType.Event, _eventStore);

            //Setup calendar to be inserted
            calendar.Title = calendarName;

            NSError error = null;

            if (!string.IsNullOrEmpty(color))
            {
                calendar.CGColor = ColorConversion.ToCGColor(color);
            }

            calendar.Source = source;

            if (_eventStore.SaveCalendar(calendar, true, out error))
            {
                return(calendar);
            }

            _eventStore.Reset();

            return(null);
        }
示例#4
0
        public void FromEventStore()
        {
            EKEventStore store = new EKEventStore();
            var          c     = EKCalendar.FromEventStore(store);

            // defaults
            Assert.True(c.AllowsContentModifications, "AllowsContentModifications");
            Assert.NotNull(c.CalendarIdentifier, "CalendarIdentifier");
            Assert.Null(c.CGColor, "CGColor");

            if (TestRuntime.CheckSystemAndSDKVersion(6, 0))
            {
                // default value changed for iOS 6.0 beta 1
                Assert.False(c.Immutable, "Immutable");
                // new in 6.0
                Assert.AreEqual(EKEntityMask.Event, c.AllowedEntityTypes, "AllowedEntityTypes");
            }
            else
            {
                Assert.True(c.Immutable, "Immutable");
            }

            Assert.Null(c.Source, "Source");
            Assert.False(c.Subscribed, "Subscribed");
            Assert.That(c.SupportedEventAvailabilities, Is.EqualTo(EKCalendarEventAvailability.None), "SupportedEventAvailabilities");
            Assert.Null(c.Title, "Title");
            Assert.That(c.Type, Is.EqualTo(EKCalendarType.Local), "Type");
        }
示例#5
0
        public void FromEventStoreWithReminder()
        {
            if (!TestRuntime.CheckXcodeVersion(4, 5))
            {
                Assert.Inconclusive("+[EKCalendar calendarForEntityType:eventStore:]: unrecognized selector before 6.0");
            }

            var c = EKCalendar.Create(EKEntityType.Reminder, new EKEventStore());

            // defaults
#if __WATCHOS__
            Assert.False(c.AllowsContentModifications, "AllowsContentModifications");
#else
            Assert.True(c.AllowsContentModifications, "AllowsContentModifications");
#endif
            Assert.NotNull(c.CalendarIdentifier, "CalendarIdentifier");
            Assert.Null(c.CGColor, "CGColor");

#if __WATCHOS__
            Assert.True(c.Immutable, "Immutable");
#else
            Assert.False(c.Immutable, "Immutable");
#endif
            Assert.Null(c.Source, "Source");
            Assert.False(c.Subscribed, "Subscribed");
            Assert.That(c.SupportedEventAvailabilities, Is.EqualTo(EKCalendarEventAvailability.None), "SupportedEventAvailabilities");
            Assert.Null(c.Title, "Title");
            Assert.That(c.Type, Is.EqualTo(EKCalendarType.Local), "Type");
            Assert.AreEqual(EKEntityMask.Reminder, c.AllowedEntityTypes, "AllowedEntityTypes");
            Assert.IsNotNull(c.CalendarIdentifier, "CalendarIdentifier");
        }
        private EKCalendar CreateEKCalendar(string calendarName, string color = null)
        {
            var calendar = EKCalendar.Create(EKEntityType.Event, _eventStore);

            calendar.Source = _eventStore.Sources.First(source => source.SourceType == EKSourceType.Local);
            calendar.Title  = calendarName;

            if (!string.IsNullOrEmpty(color))
            {
                calendar.CGColor = ColorConversion.ToCGColor(color);
            }

            NSError error = null;

            if (!_eventStore.SaveCalendar(calendar, true, out error))
            {
                // Without this, the eventStore may return the new calendar even though the save failed.
                // (this obviously also resets any other changes, but since we own the eventStore
                //  we can be pretty confident that won't be an issue)
                //
                _eventStore.Reset();

                throw new PlatformException(error.LocalizedDescription, new NSErrorException(error));
            }

            return(calendar);
        }
示例#7
0
        public void FromEventStore_Null()
        {
#if MONOMAC
            EKCalendar.Create(EKEntityType.Event, null);
#else
            EKCalendar.FromEventStore(null);
#endif
        }
示例#8
0
 /// <summary>
 /// Initializes the <see cref="U3DXT.iOS.Personal.PersonalXT"/> class.
 /// </summary>
 public static void Init()
 {
     eventStore = new EKEventStore();
     if (GetCalendarAccessStatus() == "Authorized")
     {
         calendar = eventStore.defaultCalendarForNewEvents;                 //for the case where it is already granted
     }
 }
示例#9
0
        public void Title()
        {
            EKEventStore store = new EKEventStore();
            var          c     = EKCalendar.FromEventStore(store);

            c.Title = "my title";
            Assert.That(c.Title, Is.EqualTo("my title"), "Title");
        }
示例#10
0
        public void FromEventStore_Null()
        {
#if MONOMAC
            Assert.Throws <ArgumentNullException> (() => EKCalendar.Create(EKEntityType.Event, null));
#else
            Assert.Throws <ArgumentNullException> (() => EKCalendar.FromEventStore(null));
#endif
        }
示例#11
0
        public void FromEventStore()
        {
            RequestPermission();

            EKEventStore store = new EKEventStore();

#if MONOMAC || __MACCATALYST__
            var c = EKCalendar.Create(EKEntityType.Event, store);
#else
            var c = EKCalendar.FromEventStore(store);
#endif
            // defaults
#if __WATCHOS__
            Assert.False(c.AllowsContentModifications, "AllowsContentModifications");
#else
            Assert.True(c.AllowsContentModifications, "AllowsContentModifications");
#endif
            Assert.NotNull(c.CalendarIdentifier, "CalendarIdentifier");
#if MONOMAC
            Assert.Null(c.Color, "Color");
#else
            Assert.Null(c.CGColor, "CGColor");
#endif

            if (TestRuntime.CheckXcodeVersion(4, 5))
            {
                // default value changed for iOS 6.0 beta 1
#if __WATCHOS__
                Assert.True(c.Immutable, "Immutable");
#else
                Assert.False(c.Immutable, "Immutable");
#endif
                // new in 6.0
                Assert.AreEqual(EKEntityMask.Event, c.AllowedEntityTypes, "AllowedEntityTypes");
            }
            else
            {
                Assert.True(c.Immutable, "Immutable");
            }

            Assert.Null(c.Source, "Source");
            Assert.False(c.Subscribed, "Subscribed");
#if MONOMAC || __MACCATALYST__
            Assert.That(c.SupportedEventAvailabilities, Is.EqualTo(EKCalendarEventAvailability.Busy | EKCalendarEventAvailability.Free), "SupportedEventAvailabilities");
            Assert.That(c.Title, Is.EqualTo(string.Empty), "Title");
#else
            Assert.That(c.SupportedEventAvailabilities, Is.EqualTo(EKCalendarEventAvailability.None), "SupportedEventAvailabilities");
            if (TestRuntime.CheckXcodeVersion(13, 2))
            {
                Assert.That(c.Title, Is.EqualTo(string.Empty), "Title");
            }
            else
            {
                Assert.Null(c.Title, "Title");
            }
#endif
            Assert.That(c.Type, Is.EqualTo(EKCalendarType.Local), "Type");
        }
示例#12
0
        /// <summary>
        /// Creates a new calendar or updates the name and color of an existing one.
        /// </summary>
        /// <param name="calendar">The calendar to create/update</param>
        /// <exception cref="System.ArgumentException">Calendar does not exist on device or is read-only</exception>
        /// <exception cref="System.UnauthorizedAccessException">Calendar access denied</exception>
        /// <exception cref="Calendars.Plugin.Abstractions.PlatformException">Unexpected platform-specific error</exception>
        public async Task AddOrUpdateCalendarAsync(Calendar calendar)
        {
            await RequestCalendarAccess().ConfigureAwait(false);

            EKCalendar deviceCalendar = null;

            if (!string.IsNullOrEmpty(calendar.ExternalID))
            {
                deviceCalendar = _eventStore.GetCalendar(calendar.ExternalID);

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

            if (deviceCalendar == null)
            {
                deviceCalendar      = CreateEKCalendar(calendar.Name, calendar.Color);
                calendar.ExternalID = deviceCalendar.CalendarIdentifier;

                // Update color in case iOS assigned one
                if (deviceCalendar?.CGColor != null)
                {
                    calendar.Color = ColorConversion.ToHexColor(deviceCalendar.CGColor);
                }
            }
            else
            {
                deviceCalendar.Title = calendar.Name;

                if (!string.IsNullOrEmpty(calendar.Color))
                {
                    deviceCalendar.CGColor = ColorConversion.ToCGColor(calendar.Color);
                }

                NSError error = null;
                if (!_eventStore.SaveCalendar(deviceCalendar, true, out error))
                {
                    // Without this, the eventStore will continue to return the "updated"
                    // calendar even though the save failed!
                    // (this obviously also resets any other changes, but since we own the eventStore
                    //  we can be pretty confident that won't be an issue)
                    //
                    _eventStore.Reset();

                    if (error.Domain == _ekErrorDomain && error.Code == (int)EKErrorCode.CalendarIsImmutable)
                    {
                        throw new ArgumentException(error.LocalizedDescription, new NSErrorException(error));
                    }
                    else
                    {
                        throw new PlatformException(error.LocalizedDescription, new NSErrorException(error));
                    }
                }
            }
        }
示例#13
0
 /// <summary>
 /// Creates a new Calendars.Plugin.Abstractions.Calendar from an EKCalendar
 /// </summary>
 /// <param name="ekCalendar">Source EKCalendar</param>
 /// <returns>Corresponding Calendars.Plugin.Abstractions.Calendar</returns>
 public static Calendar ToCalendar(this EKCalendar ekCalendar)
 {
     return(new Calendar
     {
         Name = ekCalendar.Title,
         ExternalID = ekCalendar.CalendarIdentifier,
         CanEditCalendar = ekCalendar.AllowsContentModifications,
         CanEditEvents = ekCalendar.AllowsContentModifications,
         Color = ColorConversion.ToHexColor(ekCalendar.CGColor)
     });
 }
示例#14
0
        public void Title()
        {
            EKEventStore store = new EKEventStore();

#if MONOMAC
            var c = EKCalendar.Create(EKEntityType.Event, store);
#else
            var c = EKCalendar.FromEventStore(store);
#endif
            c.Title = "my title";
            Assert.That(c.Title, Is.EqualTo("my title"), "Title");
        }
示例#15
0
        /// <summary>
        /// _s the request access to calendar handler.
        /// </summary>
        /// <param name="granted">If set to <c>true</c> granted.</param>
        /// <param name="arg2">Arg2.</param>
        private static void _RequestAccessToCalendarHandler(bool granted, NSError arg2)
        {
            if (granted)
            {
                calendar = eventStore.defaultCalendarForNewEvents;
            }

            if (_calendarGrantedHandlers != null)
            {
                _calendarGrantedHandlers(null, new GrantedEventArgs(granted));
            }
        }
示例#16
0
		public PNVModel ()
		{
			EventStore = new EKEventStore ();

			EventStore.RequestAccess(EKEntityType.Event, delegate (bool arg1, NSError arg2) {
				if (arg2 != null) {
					Console.WriteLine (arg2.ToString ());
				}
			});

			SelectedCalendar = EventStore.DefaultCalendarForNewEvents;
		}
示例#17
0
        public PNVModel()
        {
            EventStore = new EKEventStore();

            EventStore.RequestAccess(EKEntityType.Event, delegate(bool arg1, NSError arg2) {
                if (arg2 != null)
                {
                    Console.WriteLine(arg2.ToString());
                }
            });

            SelectedCalendar = EventStore.DefaultCalendarForNewEvents;
        }
示例#18
0
        /// <summary>
        /// Creates a new Calendars.Plugin.Abstractions.Calendar from an EKCalendar
        /// </summary>
        /// <param name="ekCalendar">Source EKCalendar</param>
        /// <returns>Corresponding Calendars.Plugin.Abstractions.Calendar</returns>
        public static Calendar ToCalendar(this EKCalendar ekCalendar)
        {
            System.Console.WriteLine($"Calendar: {ekCalendar.Title}, Source: {ekCalendar.Source.Title}, {ekCalendar.Source.SourceType}");

            return(new Calendar
            {
                Name = ekCalendar.Title,
                ExternalID = ekCalendar.CalendarIdentifier,
                CanEditCalendar = ekCalendar.AllowsContentModifications,
                CanEditEvents = ekCalendar.AllowsContentModifications,
                Color = ColorConversion.ToHexColor(ekCalendar.CGColor)
            });
        }
示例#19
0
        public void Title()
        {
            RequestPermission();

            EKEventStore store = new EKEventStore();

#if MONOMAC || __MACCATALYST__
            var c = EKCalendar.Create(EKEntityType.Event, store);
#else
            var c = EKCalendar.FromEventStore(store);
#endif
            c.Title = "my title";
            Assert.That(c.Title, Is.EqualTo("my title"), "Title");
        }
示例#20
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();
            }
        }
示例#21
0
        /// <summary>
        /// Creates a new Calendars.Plugin.Abstractions.Calendar from an EKCalendar
        /// </summary>
        /// <param name="ekCalendar">Source EKCalendar</param>
        /// <returns>Corresponding Calendars.Plugin.Abstractions.Calendar</returns>
        public static Calendar ToCalendar(this EKCalendar ekCalendar)
        {
            xLog.Debug($"Calendar: {ekCalendar.Title}, Source: {ekCalendar.Source.Title}, {ekCalendar.Source.SourceType}");

            return(new Calendar
            {
                Name = ekCalendar.Title,
                ExternalID = ekCalendar.CalendarIdentifier,
                CanEditCalendar = !ekCalendar.Immutable,
                CanEditEvents = ekCalendar.AllowsContentModifications,
                Color = ColorConversion.ToHexColor(ekCalendar.CGColor),
                AccountName = ekCalendar.Source.Title
            });
        }
示例#22
0
        /// <summary>
        /// Creates the simple event.
        /// </summary>
        /// <param name="titleTxt">Title text.</param>
        /// <param name="fromDate">From date.</param>
        /// <param name="toDate">To date.</param>
        public static void CreateSimpleEvent(string titleTxt, DateTime fromDate, DateTime toDate)
        {
            EKEvent newEvent = EKEvent.Event(eventStore);

            calendar = eventStore.defaultCalendarForNewEvents;
            Debug.Log("in CreateSimpleEvent, output of calendar: " + calendar);
            newEvent.title     = titleTxt;
            newEvent.startDate = fromDate;
            newEvent.endDate   = toDate;
            newEvent.calendar  = calendar;

            eventStore.SaveEvent(newEvent, EKSpan.ThisEvent, null);
            eventStore.SaveCalendar(calendar, true, null);
            eventStore.Commit(null);
        }
示例#23
0
        public async Task <bool> CreateCalendarForAppAlarmsAsync()
        {
            bool hasPermission = await ASkForPermissionsAsync();

            if (hasPermission && appCalendar == null)
            {
                appCalendar         = EKCalendar.Create(EKEntityType.Event, eventsStore);
                appCalendar.Title   = "My App Calendar";
                appCalendar.Source  = eventsStore.Sources.Where(s => s.SourceType == EKSourceType.CalDav).FirstOrDefault();
                appCalendar.CGColor = UIColor.Purple.CGColor;
                bool saved = eventsStore.SaveCalendar(appCalendar, true, out NSError e);
                return(saved);
            }
            return(true);
        }
示例#24
0
        private Task <bool> ASkForPermissionsAsync()
        {
            TaskCompletionSource <bool> tcs = new TaskCompletionSource <bool>();

            eventsStore.RequestAccess(EKEntityType.Event, (bool granted, NSError error) =>
            {
                if (!granted)
                {
                    var alert = UIAlertController.Create("Acceso denegado", "Acceso al calendario denegado por el usuario", UIAlertControllerStyle.Alert);
                    UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(alert, true, null);
                }
                else
                {
                    appCalendar = eventsStore.Calendars.Where(c => c.Title.ToLowerInvariant().Equals(calendarTitle.ToLowerInvariant())).FirstOrDefault();
                }
                tcs.SetResult(granted);
            });

            return(tcs.Task);
        }
示例#25
0
        partial void showCalendarChooser(UIKit.UIBarButtonItem sender)
        {
            // Show the EKCalendarChooser
            var calendarChooser = new EKCalendarChooser(EKCalendarChooserSelectionStyle.Single,
                                                        EKCalendarChooserDisplayStyle.WritableCalendarsOnly,
                                                        model.EventStore);

            calendarChooser.ShowsDoneButton   = true;
            calendarChooser.ShowsCancelButton = false;
            calendarChooser.SelectionChanged += (object obj, EventArgs e) =>
            {
                // Called whenever the selection is changed by the user
                model.SelectedCalendar = (EKCalendar)calendarChooser.SelectedCalendars.AnyObject;
                Title = model.SelectedCalendar.Title;
            };
            calendarChooser.Finished += (object obj, EventArgs e) =>
            {
                // These are called when the corresponding button is pressed to dismiss the
                // controller. It is up to the recipient to dismiss the chooser.
                model.FetchPokerEvents();
                DismissViewController(true, null);
            };
            calendarChooser.SelectionChanged += (object obj, EventArgs e) =>
            {
                // Update our events, since the selected calendar may have changed.
                model.SelectedCalendar = (EKCalendar)calendarChooser.SelectedCalendars.AnyObject;
                Title = model.SelectedCalendar.Title;
            };

            if (model.SelectedCalendar != null)
            {
                EKCalendar[] temp = new EKCalendar [1];
                temp [0] = model.SelectedCalendar;
                var selectedCalendars = new NSSet(temp);
                calendarChooser.SelectedCalendars = selectedCalendars;
            }

            UINavigationController navigationController = new UINavigationController(calendarChooser);

            PresentViewController(navigationController, true, null);
        }
示例#26
0
 public void FromEventStore_Null()
 {
     EKCalendar.FromEventStore(null);
 }
示例#27
0
 /// <summary>
 /// Initializes the <see cref="U3DXT.iOS.Personal.PersonalXT"/> class.
 /// </summary>
 public static void Init()
 {
     eventStore = new EKEventStore();
     calendar = eventStore.defaultCalendarForNewEvents;
 }
示例#28
0
 public bool RemoveCalendarc(EKCalendar calendar, bool commit, out NSError error)
 {
     return(RemoveCalendar(calendar, commit, out error));
 }
示例#29
0
文件: PersonalXT.cs 项目: BiDuc/u3dxt
 /// <summary>
 /// Initializes the <see cref="U3DXT.iOS.Personal.PersonalXT"/> class.
 /// </summary>
 public static void Init()
 {
     eventStore = new EKEventStore();
     if(GetCalendarAccessStatus() == "Authorized")
         calendar = eventStore.defaultCalendarForNewEvents; //for the case where it is already granted
 }
示例#30
0
        private void AddGoHejaCalendarToDevice()
        {
            try
            {
                NSError error;

                ////remove existing descending events from now in "goHeja Events" calendar of device.
                var calendars = App.Current.EventStore.GetCalendars(EKEntityType.Event);
                foreach (var calendar in calendars)
                {
                    if (calendar.Title == PortableLibrary.Constants.DEVICE_CALENDAR_TITLE)
                    {
                        goHejaCalendar = calendar;

                        EKCalendar[] calendarArray = new EKCalendar[1];
                        calendarArray[0] = calendar;
                        NSPredicate pEvents   = App.Current.EventStore.PredicateForEvents(NSDate.Now.AddSeconds(-(3600 * 10000)), NSDate.Now.AddSeconds(3600 * 10000), calendarArray);
                        EKEvent[]   allEvents = App.Current.EventStore.EventsMatching(pEvents);
                        if (allEvents == null)
                        {
                            continue;
                        }
                        foreach (var pEvent in allEvents)
                        {
                            NSError  pE;
                            DateTime now         = DateTime.Now;
                            DateTime startNow    = new DateTime(now.Year, now.Month, now.Day);
                            var      startString = baseVC.ConvertDateTimeToNSDate(startNow);
                            if (pEvent.StartDate.Compare(startString) == NSComparisonResult.Descending)
                            {
                                App.Current.EventStore.RemoveEvent(pEvent, EKSpan.ThisEvent, true, out pE);
                            }
                        }
                    }
                }

                if (goHejaCalendar == null)
                {
                    goHejaCalendar = EKCalendar.Create(EKEntityType.Event, App.Current.EventStore);
                    EKSource goHejaSource = null;

                    foreach (EKSource source in App.Current.EventStore.Sources)
                    {
                        if (source.SourceType == EKSourceType.CalDav && source.Title == "iCloud")
                        {
                            goHejaSource = source;
                            break;
                        }
                    }
                    if (goHejaSource == null)
                    {
                        foreach (EKSource source in App.Current.EventStore.Sources)
                        {
                            if (source.SourceType == EKSourceType.Local)
                            {
                                goHejaSource = source;
                                break;
                            }
                        }
                    }
                    if (goHejaSource == null)
                    {
                        return;
                    }
                    goHejaCalendar.Title  = PortableLibrary.Constants.DEVICE_CALENDAR_TITLE;
                    goHejaCalendar.Source = goHejaSource;
                }

                App.Current.EventStore.SaveCalendar(goHejaCalendar, true, out error);

                if (error == null)
                {
                    AddEvents();
                }
            }
            catch (Exception e)
            {
                new UIAlertView("add events process", e.Message, null, "ok", null).Show();
            }
        }
示例#31
0
文件: PersonalXT.cs 项目: BiDuc/u3dxt
        /// <summary>
        /// _s the request access to calendar handler.
        /// </summary>
        /// <param name="granted">If set to <c>true</c> granted.</param>
        /// <param name="arg2">Arg2.</param>
        private static void _RequestAccessToCalendarHandler(bool granted, NSError arg2)
        {
            if(granted)
                calendar = eventStore.defaultCalendarForNewEvents;

            if (_calendarGrantedHandlers != null)
                _calendarGrantedHandlers(null, new GrantedEventArgs(granted));
        }
示例#32
0
文件: PersonalXT.cs 项目: BiDuc/u3dxt
        /// <summary>
        /// Creates the simple event.
        /// </summary>
        /// <param name="titleTxt">Title text.</param>
        /// <param name="fromDate">From date.</param>
        /// <param name="toDate">To date.</param>
        public static void CreateSimpleEvent(string titleTxt,DateTime fromDate, DateTime toDate )
        {
            EKEvent newEvent = EKEvent.Event(eventStore);
            calendar = eventStore.defaultCalendarForNewEvents;
            Debug.Log("in CreateSimpleEvent, output of calendar: " + calendar);
            newEvent.title = titleTxt;
            newEvent.startDate = fromDate;
            newEvent.endDate = toDate;
            newEvent.calendar = calendar;

            eventStore.SaveEvent(newEvent, EKSpan.ThisEvent, null);
            eventStore.SaveCalendar(calendar,true, null);
            eventStore.Commit(null);
        }
示例#33
0
        public static EKEvent[] FetchEvents(DateTime startDate, DateTime endDate)
        {
            // Create the predicate. Pass it the default calendar.
            //Util.WriteLine ("Getting Calendars");
            EKEventStore store = MyEventStore;
            EKCalendar[] calendarArray;
            if (MyCalendar == null)
              calendarArray = store.Calendars;
            else
                calendarArray = new EKCalendar[] { MyCalendar };

            //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;
        }
示例#34
0
        public async Task PushMeetingsToCalendarAsync(List <Meeting> meetings)
        {
            try
            {
                using (await _PushMeetingsToCalendarAsyncLock.LockAsync())
                {
                    if (!(await _eventStore.RequestAccessAsync(EKEntityType.Event)).Item1)
                    {
                        return;
                    }

                    var     calendar   = _eventStore.GetCalendar(AcraCalendarIdentifier);
                    CGColor colorToUse = null;
                    if (calendar != null)
                    {
                        colorToUse = calendar.CGColor;
                        NSError errorToDelete;;
                        _eventStore.RemoveCalendar(calendar, true, out errorToDelete);
                    }

                    var otherToDelete = _eventStore.GetCalendars(EKEntityType.Event).Where(c => c.Title.StartsWith("ACRA"));
                    foreach (var item in otherToDelete)
                    {
                        NSError errorToDelete;
                        _eventStore.RemoveCalendar(item, true, out errorToDelete);
                    }

                    // now recreate a calendar !
                    calendar       = EKCalendar.FromEventStore(_eventStore);
                    calendar.Title = "ACRA du " + DateTime.Now.ToString("g", new System.Globalization.CultureInfo("fr"));
                    if (colorToUse != null)
                    {
                        calendar.CGColor = colorToUse;
                    }

                    EKSource[] sources     = _eventStore.Sources;
                    var        sourceToSet = sources
                                             .FirstOrDefault(s => s.SourceType == EKSourceType.CalDav && s.Title.Equals("iCloud", StringComparison.InvariantCultureIgnoreCase));

                    if (sourceToSet == null)
                    {
                        sourceToSet = sources.FirstOrDefault(s => s.SourceType == EKSourceType.Local);
                    }

                    if (sourceToSet == null)
                    {
                        sourceToSet = _eventStore.DefaultCalendarForNewEvents.Source;
                    }

                    calendar.Source = sourceToSet;
                    NSError error;
                    _eventStore.SaveCalendar(calendar, true, out error);
                    AcraCalendarIdentifier = calendar.CalendarIdentifier;

                    var toSaves = meetings.OrderByDescending(ap => ap.StartDate).ToArray();

                    var howMuch = toSaves.Length;
                    for (int index = 0; index < howMuch; index++)
                    {
                        var appointData = toSaves[index];

                        var toSave = EKEvent.FromStore(_eventStore);

                        //if (!string.IsNullOrEmpty(appointData.))
                        //{
                        //    toSave.Location = appointData.Location;
                        //}
                        toSave.StartDate = ConvertDateTimeToNSDate(appointData.StartDate);
                        toSave.AllDay    = appointData.AllDayEvent;

                        if (appointData.IsRecurrent && appointData.AllDayEvent)
                        {
                            var end  = EKRecurrenceEnd.FromEndDate(ConvertDateTimeToNSDate(appointData.EndDate));
                            var rule = new EKRecurrenceRule(EKRecurrenceFrequency.Weekly, 1, end);
                            toSave.RecurrenceRules = new[] { rule };
                        }
                        else
                        {
                            toSave.EndDate = ConvertDateTimeToNSDate(appointData.EndDate);
                        }

                        // If set to AllDay and given an EndDate of 12am the next day, EventKit
                        // assumes that the event consumes two full days.
                        // (whereas WinPhone/Android consider that one day, and thus so do we)
                        //
                        if (appointData.AllDayEvent)
                        {
                            toSave.EndDate = ConvertDateTimeToNSDate(appointData.EndDate.AddDays(-1));
                        }

                        if (!appointData.IsHoliday)
                        {
                            if (appointData.Duration.TotalDays > 1 && !appointData.IsRecurrent)
                            {
                                toSave.Title = ((int)appointData.Duration.TotalDays + 1) + " " + appointData.Title;
                            }
                            else
                            {
                                toSave.Title = appointData.Title;
                            }
                        }
                        else
                        {
                            //TODO : localisation
                            toSave.Title = "[FERIE] " + appointData.Title;
                        }

                        toSave.Notes = appointData.Type.ToString();

                        toSave.Calendar = calendar;

                        NSError errorCommit;
                        _eventStore.SaveEvent(toSave, EKSpan.ThisEvent, out errorCommit);
                    }
                }

                NSError errorEvent;

                _eventStore.Commit(out errorEvent);
            }
            catch (Exception e)
            {
                //TODO : localisation
                await App.Instance.AlertService.ShowExceptionMessageAsync(e, "Impossible de renseigner votre calendrier iOS");
            }
        }
示例#35
0
        /// <summary>
        /// Add new event to a calendar or update an existing event.
        /// Throws if Calendar ID is empty, calendar does not exist, or calendar is read-only.
        /// </summary>
        /// <param name="calendar">Destination calendar</param>
        /// <param name="calendarEvent">Event to add or update</param>
        /// <exception cref="System.ArgumentException">Calendar is not specified, does not exist on device, or is read-only</exception>
        /// <exception cref="System.UnauthorizedAccessException">Calendar access denied</exception>
        /// <exception cref="Calendars.Plugin.Abstractions.PlatformException">Unexpected platform-specific error</exception>
        public async Task AddOrUpdateEventAsync(Calendar calendar, CalendarEvent calendarEvent)
        {
            await RequestCalendarAccess().ConfigureAwait(false);

            EKCalendar deviceCalendar = null;

            if (string.IsNullOrEmpty(calendar.ExternalID))
            {
                throw new ArgumentException("Missing calendar identifier", "calendar");
            }
            else
            {
                deviceCalendar = _eventStore.GetCalendar(calendar.ExternalID);

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

            EKEvent iosEvent = null;

            // If Event already corresponds to an existing EKEvent in the target
            // Calendar, then edit that instead of creating a new one.
            //
            if (!string.IsNullOrEmpty(calendarEvent.ExternalID))
            {
                var existingEvent = _eventStore.EventFromIdentifier(calendarEvent.ExternalID);

                if (existingEvent.Calendar.CalendarIdentifier == deviceCalendar.CalendarIdentifier)
                {
                    iosEvent = existingEvent;
                }
            }

            if (iosEvent == null)
            {
                iosEvent = EKEvent.FromStore(_eventStore);
            }

            iosEvent.Title     = calendarEvent.Name;
            iosEvent.Notes     = calendarEvent.Description;
            iosEvent.AllDay    = calendarEvent.AllDay;
            iosEvent.Location  = calendarEvent.Location ?? string.Empty;
            iosEvent.StartDate = calendarEvent.Start.ToNSDate();

            // If set to AllDay and given an EndDate of 12am the next day, EventKit
            // assumes that the event consumes two full days.
            // (whereas WinPhone/Android consider that one day, and thus so do we)
            //
            iosEvent.EndDate  = calendarEvent.AllDay ? calendarEvent.End.AddMilliseconds(-1).ToNSDate() : calendarEvent.End.ToNSDate();
            iosEvent.Calendar = deviceCalendar;

            NSError error = null;

            if (!_eventStore.SaveEvent(iosEvent, EKSpan.ThisEvent, out error))
            {
                // Without this, the eventStore will continue to return the "updated"
                // event even though the save failed!
                // (this obviously also resets any other changes, but since we own the eventStore
                //  we can be pretty confident that won't be an issue)
                //
                _eventStore.Reset();

                // Technically, probably any ekerrordomain error would be an ArgumentException?
                // - but we don't necessarily know *which* argument (at least not without the code)
                // - for now, just focusing on the start > end scenario and translating the rest to PlatformException. Can always add more later.

                if (error.Domain == _ekErrorDomain && error.Code == (int)EKErrorCode.DatesInverted)
                {
                    throw new ArgumentException(error.LocalizedDescription, new NSErrorException(error));
                }
                else
                {
                    throw new PlatformException(error.LocalizedDescription, new NSErrorException(error));
                }
            }

            calendarEvent.ExternalID = iosEvent.EventIdentifier;
        }
示例#36
0
 public bool RemoveCalendarc(EKCalendar calendar, bool commit, out NSError error)
 {
     return RemoveCalendar (calendar, commit, out error);
 }
		partial void showCalendarChooser (MonoTouch.UIKit.UIBarButtonItem sender)
		{
			// Show the EKCalendarChooser
			var calendarChooser = new EKCalendarChooser (EKCalendarChooserSelectionStyle.Single, 
			                                                           EKCalendarChooserDisplayStyle.WritableCalendarsOnly,
			                                                           model.EventStore);
			calendarChooser.ShowsDoneButton = true;
			calendarChooser.ShowsCancelButton = false;
			calendarChooser.SelectionChanged += (object obj, EventArgs e) => 
			{
				// Called whenever the selection is changed by the user
				model.SelectedCalendar = (EKCalendar) calendarChooser.SelectedCalendars.AnyObject;
				Title = model.SelectedCalendar.Title;
			};
			calendarChooser.Finished += (object obj, EventArgs e) => 
			{
				// These are called when the corresponding button is pressed to dismiss the
				// controller. It is up to the recipient to dismiss the chooser.
				model.FetchPokerEvents ();
				DismissViewController (true, null);
			};
			calendarChooser.SelectionChanged += (object obj, EventArgs e) => 
			{
				// Update our events, since the selected calendar may have changed.
				model.SelectedCalendar = (EKCalendar) calendarChooser.SelectedCalendars.AnyObject;
				Title = model.SelectedCalendar.Title;
			};

			if (model.SelectedCalendar != null) {
				EKCalendar[] temp = new EKCalendar [1];
				temp [0] = model.SelectedCalendar;
				var selectedCalendars = new NSSet (temp);
				calendarChooser.SelectedCalendars = selectedCalendars;
			}

			UINavigationController navigationController = new UINavigationController (calendarChooser);
			PresentViewController (navigationController, true, null);
		}
 private UserCalendar userCalendarFromEKCalendar(EKCalendar calendar)
 => new UserCalendar(
     calendar.CalendarIdentifier,
     calendar.Title,
     calendar.Source.Title);
示例#39
0
 public static EKEvent getEvent(CalendarDayEventView theEventView)
 {
     EKEventStore store = MyEventStore;
     EKCalendar[] calendarArray;
     if (MyCalendar == null)
       calendarArray = store.Calendars;
     else
         calendarArray = new EKCalendar[] { MyCalendar };
     //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 ();
 }