public EventsList(IICalendarCollection iCalCollection, bool isAutomaticSyncChecked, int? syncTimerInterval, string calendarName, Uri url, string username, string password, string serverAddress)
        {
            try
            {
                InitializeComponent();
                CenterToScreen();
                IsClosed = false;
                CalCollection = iCalCollection;
                CalendarName = calendarName;
                ServerUrl = url;
                Username = username;
                Password = password;
                IsAutomaticSyncChecked = isAutomaticSyncChecked;
                SyncTimerInterval = syncTimerInterval;
                ServerAddress = serverAddress;

                PopulateEventsList();
                SetNotificationTimer();
                SetSyncTimer(IsAutomaticSyncChecked, SyncTimerInterval);
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }
Beispiel #2
0
        public void AddEventsToWorkCalendar(string icalPath)
        {
            IICalendarCollection calendars      = Ical.Net.Calendar.LoadFromFile(icalPath);
            List <Event>         eventsToCreate = GetEventsFromIcal(calendars);

            UploadEvents(eventsToCreate);
        }
Beispiel #3
0
        private void icsParse(object sender, EventArgs e)
        {
            textBox1.Clear();
            OpenFileDialog icsReader = new OpenFileDialog();

            icsReader.InitialDirectory = Environment.CurrentDirectory;
            if (icsReader.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    IICalendarCollection calendarCollection = Calendar.LoadFromFile(icsReader.FileName);
                    foreach (Calendar c in calendarCollection)
                    {
                        foreach (Event eve in c.Events)
                        {
                            //As far as I can tell, the first category is always the class name. This is what we want.
                            textBox1.AppendText(eve.Categories[0] + ": " + eve.Summary + " by " + eve.DtEnd + Environment.NewLine);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: " + ex.Message);
                }
            }
        }
        public static List <IEvent> parseics(String path)
        {
            try
            {
                IICalendarCollection    calendars    = iCalendar.LoadFromFile(@path);
                List <IDateTime>        listdatetime = new List <IDateTime>();
                List <DDay.iCal.IEvent> listevent    = new List <DDay.iCal.IEvent>();

                IList <Occurrence> occurrences = calendars.GetOccurrences(new DateTime(2017, 1, 1), new DateTime(2018, 3, 26));


                int i = 0;
                foreach (Occurrence occurrence in occurrences)
                {
                    DateTime            occurrenceTime = occurrence.Period.StartTime.Local.AddHours(1);
                    IRecurringComponent rc             = occurrence.Source as IRecurringComponent;
                    if (rc != null)
                    {
                        rc.Calendar.Events[i].Start.AddHours(1);
                        rc.Calendar.Events[i].End.AddHours(1);
                        listevent.Add(rc.Calendar.Events[i]);
                        i++;
                    }
                }

                return(listevent);
            }
            catch (Exception e) {
                Console.WriteLine("ERREUR : " + e.Message);
                return(null);
            }
        }
Beispiel #5
0
 static public IICalendarCollection LoadFromFile(string filepath, Encoding encoding, ISerializer serializer)
 {
     // NOTE: Fixes bug #3211934 - Bug in iCalendar.cs - UnauthorizedAccessException
     using (FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read))
     {
         IICalendarCollection calendars = LoadFromStream(fs, encoding, serializer);
         return(calendars);
     }
 }
Beispiel #6
0
    public void GetNewEvents()
    {
        List <CSVEvent> AllEvents  = new List <CSVEvent>();
        List <CSVEvent> NewEvents  = new List <CSVEvent>();
        List <CSVEvent> LastImport = new List <CSVEvent>();

        try
        {
            IICalendarCollection feed = iCalUtility.Deserialize(url);
            foreach (IEvent e in feed.SelectMany(e => e.Events))
            {
                CSVEvent ev = new CSVEvent
                {
                    EventName    = Encoding.UTF8.GetString(Encoding.Default.GetBytes(e.Summary)),
                    YearLevel    = e.Categories.FirstOrDefault(),
                    Cost         = e.Properties.Get <string>("X-COST"),
                    Location     = e.Location,
                    StartDate    = e.Start.Date,
                    FinishDate   = e.DTEnd.Date,
                    OtherDetails = e.Description
                };
                if (e.Start.HasTime && !e.IsAllDay)
                {
                    ev.StartTime = e.Start.Date.Add(e.Start.TimeOfDay);
                }
                if (e.End.HasTime)
                {
                    ev.FinishTime = e.DTEnd.Date.Add(e.DTEnd.TimeOfDay);
                }
                AllEvents.Add(ev);
            }
            if (File.Exists(HttpContext.Current.Server.MapPath("~/LastImport.csv")))
            {
                LastImport = cc.Read <CSVEvent>(HttpContext.Current.Server.MapPath("~/LastImport.csv"), InputFileDescription).ToList();
            }
            NewEvents = AllEvents.Except(LastImport).ToList();
        }
        catch (Exception ex)
        {
            using (StreamWriter writer = new StreamWriter(HttpContext.Current.Server.MapPath("~/log.txt"), true))
            {
                writer.WriteLine("Message :" + ex.Message + "\n" + Environment.NewLine + "StackTrace :" + ex.StackTrace +
                                 "" + Environment.NewLine + "Date :" + DateTime.Now.ToString());
                writer.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine);
            }
        }
        if (NewEvents.Count > 0)
        {
            cc.Write(NewEvents, HttpContext.Current.Server.MapPath("~/NewEvents.csv"), InputFileDescription);
            cc.Write(AllEvents, HttpContext.Current.Server.MapPath("~/LastImport.csv"), InputFileDescription);
            Clients.Caller.Download("NewEvents.csv");
        }
        else
        {
            Clients.Caller.NoNewEvents();
        }
    }
Beispiel #7
0
        static public IICalendarCollection LoadFromFile(string filepath, Encoding encoding, ISerializer serializer)
        {
            FileStream fs = new FileStream(filepath, FileMode.Open);

            IICalendarCollection calendars = LoadFromStream(fs, encoding, serializer);

            fs.Close();
            return(calendars);
        }
Beispiel #8
0
        static public IICalendarCollection LoadFromStream(TextReader tr, ISerializer serializer)
        {
            string               text       = tr.ReadToEnd();
            MemoryStream         ms         = new MemoryStream(Encoding.UTF8.GetBytes(text));
            IICalendarCollection collection = LoadFromStream(ms, Encoding.UTF8, serializer);

            ms.Dispose();

            return(collection);
        }
        public override void Init()
        {
            calendars = iCalendar.LoadFromUri(new Uri("http://www.piraten-partei.ch/calendar-event/ical"));

            foreach (var calendar in calendars)
            {
                foreach (var @event in calendar.Events)
                {
                    Console.WriteLine(@event.Location);
                    Console.WriteLine(@event.Start.ToString());
                }
            }
        }
        public override void Init()
        {
            calendars = iCalendar.LoadFromUri(new Uri("http://www.piraten-partei.ch/calendar-event/ical"));

            foreach (var calendar in calendars)
            {
                foreach (var @event in calendar.Events)
                {
                    Console.WriteLine(@event.Location);
                    Console.WriteLine(@event.Start.ToString());
                }
            }
        }
        public EventsList(IICalendarCollection iCalCollection, bool isAutomaticSyncChecked, int? syncTimerInterval, string calendarName, Uri url, string username, string password, string serverAddress)
        {
            try
            {
                DrawControls();
                IsClosed = false;
                CalCollection = iCalCollection;
                CalendarName = calendarName;
                ServerUrl = url;
                Username = username;
                Password = password;
                IsAutomaticSyncChecked = isAutomaticSyncChecked;
                SyncTimerInterval = syncTimerInterval;
                ServerAddress = serverAddress;

                PopulateEventsList();
                SetNotificationTimer();
                SetSyncTimer(IsAutomaticSyncChecked, SyncTimerInterval);

                btnSyncNow.Clicked += delegate
                {
                    btnSyncNow_Click();
                };

                btnEventManagment.Clicked += delegate
                {
                    btnEventManagment_Click();
                };

                btnSettings.Clicked += delegate
                {
                    btnSettings_Click();
                };

                btnLogOut.Clicked += delegate
                {
                    btnLogOut_Click();
                };

                btnQuit.Clicked += delegate
                {
                    btnQuit_Click();
                };
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }
Beispiel #12
0
        /// <summary>
        /// The main program execution.
        /// </summary>
        static void Main(string[] args)
        {
            // Create a new iCalendar
            iCalendar iCal = new iCalendar();

            // Create the event, and add it to the iCalendar
            Event evt = iCal.Create <Event>();

            // Set information about the event
            evt.Start       = iCalDateTime.Today.AddHours(8);
            evt.End         = evt.Start.AddHours(18); // This also sets the duration
            evt.Description = "The event description";
            evt.Location    = "Event location";
            evt.Summary     = "18 hour event summary";

            // Set information about the second event
            evt          = iCal.Create <Event>();
            evt.Start    = iCalDateTime.Today.AddDays(5);
            evt.End      = evt.Start.AddDays(1);
            evt.IsAllDay = true;
            evt.Summary  = "All-day event";

            // Display each event
            foreach (Event e in iCal.Events)
            {
                Console.WriteLine("Event created: " + GetDescription(e));
            }

            // Serialize (save) the iCalendar
            iCalendarSerializer serializer = new iCalendarSerializer();

            serializer.Serialize(iCal, @"iCalendar.ics");
            Console.WriteLine("iCalendar file saved." + Environment.NewLine);

            // Load the calendar from the file we just saved
            IICalendarCollection calendars = iCalendar.LoadFromFile(@"iCalendar.ics");

            Console.WriteLine("iCalendar file loaded.");

            // Iterate through each event to display its description
            // (and verify the file saved correctly)
            foreach (IICalendar calendar in calendars)
            {
                foreach (IEvent e in calendar.Events)
                {
                    Console.WriteLine("Event loaded: " + GetDescription(e));
                }
            }
        }
Beispiel #13
0
        static void DoCalendarStuff()
        {
            IICalendarCollection calendars = iCalendar.LoadFromFile(@"a.ics");

            // Termine in den nächsten 2 Tagen finden. Wenn gefunden: Alarmicon!
            IList <Occurrence> occurrences = calendars.GetOccurrences(DateTime.Today.AddDays(1), DateTime.Today.AddDays(2));

            foreach (Occurrence occurrence in occurrences)
            {
                DateTime occurrenceTime = occurrence.Period.StartTime.Local;
                if (occurrence.Source is IRecurringComponent rc)
                {
                    if (CheckMessage(rc.Summary, occurrenceTime))
                    {
                        text += rc.Summary + ": " + occurrenceTime.ToShortDateString() + CRLF;
                    }
                }
            }

            // Wenn Termine gefunden, dann Alarmicon. Sonst den Nächstbesten suchen, aber keinen Alarm und kein Balloon.
            if (text != "")
            {
                lock (notifyIcon)
                {
                    notifyIcon.Icon = iconAchtung;
                    ShowBalloon();
                }
            }
            else
            {
                // Wenn keine Termime in den nächsten 2 Tagen anliegen, dann den nächsten suchen, aber Icon nicht setzen und
                // Balloon nicht auslösen
                occurrences = calendars.GetOccurrences(DateTime.Today.AddDays(3), DateTime.Today.AddDays(365));
                foreach (Occurrence occurrence in occurrences)
                {
                    DateTime occurrenceTime = occurrence.Period.StartTime.Local;
                    if (occurrence.Source is IRecurringComponent rc)
                    {
                        if (CheckMessage(rc.Summary, occurrenceTime))
                        {
                            text = "Nächster: " + rc.Summary + ": " + occurrenceTime.ToShortDateString() + CRLF;
                            break;
                        }
                    }
                }
            }
        }
Beispiel #14
0
        protected List <string> GetUpcomingEvents(string filepath)
        {
            IICalendarCollection calendars    = Calendar.LoadFromFile(Path.Combine(@"C:\ICSFiles\" + filepath + ".ics"));
            IList <Occurrence>   occurrencesn = calendars.GetOccurrences(DateTime.Today.AddDays(1), DateTime.Today.AddDays(7)).ToList();
            List <string>        Events       = new List <string>();

            foreach (Occurrence occurrence in occurrencesn)
            {
                DateTime            occurrenceTime  = occurrence.Period.StartTime.AsSystemLocal;
                DateTime            occurrenceTimee = occurrence.Period.EndTime.AsSystemLocal;
                IRecurringComponent rc = occurrence.Source as IRecurringComponent;
                if (rc != null)
                {
                    Events.Add(rc.Summary + ": " + occurrenceTime.ToShortTimeString() + " - " + occurrenceTimee.ToShortTimeString());
                }
            }

            return(Events);
        }
Beispiel #15
0
        protected void loadButton_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                string saveDir = @"\Calendars\";
                string appPath = Request.PhysicalApplicationPath;
                //Getting the duration and max days to check
                int  durationMinutes, maxDays;
                bool minutesInputBool = int.TryParse(minutesInput.Text, out durationMinutes);
                bool maxDaysBool      = int.TryParse(maxDaysInput.Text, out maxDays);
                if (FileUpload1.HasFile && FileUpload2.HasFile)
                {
                    //Saving both calendars
                    string savePath1 = appPath + saveDir + Server.HtmlEncode(FileUpload1.FileName);
                    FileUpload1.SaveAs(savePath1);
                    string savePath2 = appPath + saveDir + Server.HtmlEncode(FileUpload2.FileName);
                    FileUpload2.SaveAs(savePath2);

                    //Creating the calendars and getting the occurences (events).
                    IICalendarCollection firstCalendar  = iCalendar.LoadFromFile(savePath1);
                    IICalendarCollection secondCalendar = iCalendar.LoadFromFile(savePath2);
                    IList <Occurrence>   occurrences1   = firstCalendar.GetOccurrences(DateTime.Today, DateTime.Today.AddDays(maxDays));
                    IList <Occurrence>   occurrences2   = secondCalendar.GetOccurrences(DateTime.Today, DateTime.Today.AddDays(maxDays));
                    List <DateTime>      freeSlots      = new List <DateTime>();

                    //This list will contain all the occurences from both calendars
                    List <Occurrence> allOccurences = new List <Occurrence>();
                    //Merging the calendars into @allOccurences
                    mergeCalendars(occurrences1, occurrences2, allOccurences);
                    //Finding free spots
                    findFreeSpots(durationMinutes, maxDays, freeSlots, allOccurences);

                    Label1.Text = "This options are available:<br />";
                    //Printing all the available spots
                    foreach (DateTime dt in freeSlots)
                    {
                        Label1.Text += dt.ToShortDateString() + " at " + dt.ToShortTimeString() + "<br />";
                    }
                }
                minutesInput.Text = "";
                maxDaysInput.Text = "";
            }
        }
Beispiel #16
0
        static void Main(string[] args)
        {
            // Load the calendar file
            IICalendarCollection calendars = iCalendar.LoadFromFile(@"Business.ics");

            //
            // Get all events that occur today.
            //
            IList <Occurrence> occurrences = calendars.GetOccurrences(DateTime.Today, DateTime.Today.AddDays(1));

            Console.WriteLine("Today's Events:");

            // Iterate through each occurrence and display information about it
            foreach (Occurrence occurrence in occurrences)
            {
                DateTime            occurrenceTime = occurrence.Period.StartTime.Local;
                IRecurringComponent rc             = occurrence.Source as IRecurringComponent;
                if (rc != null)
                {
                    Console.WriteLine(rc.Summary + ": " + occurrenceTime.ToShortTimeString());
                }
            }

            //
            // Get all occurrences for the next 7 days, starting tomorrow.
            //
            occurrences = calendars.GetOccurrences(DateTime.Today.AddDays(1), DateTime.Today.AddDays(7));

            Console.WriteLine(Environment.NewLine + "Upcoming Events:");

            // Start with tomorrow
            foreach (Occurrence occurrence in occurrences)
            {
                DateTime            occurrenceTime = occurrence.Period.StartTime.Local;
                IRecurringComponent rc             = occurrence.Source as IRecurringComponent;
                if (rc != null)
                {
                    Console.WriteLine(rc.Summary + ": " + occurrenceTime.ToString());
                }
            }
        }
        /// <summary>
        ///     Deserializes the specified tr.
        /// </summary>
        /// <param name="tr">The tr.</param>
        /// <returns></returns>
        public override object Deserialize(TextReader tr)
        {
            if (tr != null)
            {
                // Normalize the text before parsing it
                tr = TextUtil.Normalize(tr, SerializationContext);

                // Create a lexer for our text stream
                var lexer  = new iCalLexer(tr);
                var parser = new iCalParser(lexer);

                // Parse the iCalendar(s)!
                IICalendarCollection iCalendars = parser.icalendar(SerializationContext);

                // Close our text stream
                tr.Close( );

                // Return the parsed iCalendar(s)
                return(iCalendars);
            }
            return(null);
        }
Beispiel #18
0
        private List <Event> GetEventsFromIcal(IICalendarCollection calendars)
        {
            var eventsToCreate = new List <Event>();

            foreach (IEvent eventItem in calendars.First().Events)
            {
                Event googleEvent = new Event();
                googleEvent.ICalUID   = eventItem.Uid;
                googleEvent.Organizer = new Event.OrganizerData
                {
                    DisplayName = eventItem.Organizer.CommonName,
                };
                googleEvent.Attendees = new List <EventAttendee>();
                foreach (var attendee in eventItem.Attendees)
                {
                    googleEvent.Attendees.Add(new EventAttendee
                    {
                        DisplayName = attendee.CommonName
                    });
                }
                googleEvent.Start = new EventDateTime
                {
                    DateTime = eventItem.Start.Date,
                    TimeZone = eventItem.Start.TimeZoneName
                };

                googleEvent.End = new EventDateTime
                {
                    DateTime = eventItem.End.Date,
                    TimeZone = eventItem.End.TimeZoneName
                };

                googleEvent.Description = eventItem.Description;

                eventsToCreate.Add(googleEvent);
            }

            return(eventsToCreate);
        }
        public static IValidator Create(Type validatorType, IResourceManager mgr, IICalendarCollection calendars, string iCalendarText)
        {
            IValidator validator = null;

            if (validatorType != null)
            {
                ConstructorInfo ci = null;

                if (iCalendarText != null)
                {
                    if (!_CalendarPlusTextConstructor.ContainsKey(validatorType))
                        _CalendarPlusTextConstructor[validatorType] = validatorType.GetConstructor(new Type[] { typeof(IResourceManager), typeof(string), typeof(IICalendarCollection) });
                    ci = _CalendarPlusTextConstructor[validatorType];
                    if (ci != null)
                        validator = ci.Invoke(new object[] { mgr, iCalendarText, calendars }) as IValidator;
                    else
                    {
                        if (!_TextConstructor.ContainsKey(validatorType))
                            _TextConstructor[validatorType] = validatorType.GetConstructor(new Type[] { typeof(IResourceManager), typeof(string) });
                        ci = _TextConstructor[validatorType];
                        if (ci != null)
                            validator = ci.Invoke(new object[] { mgr, iCalendarText }) as IValidator;
                    }
                }
                if (validator == null)
                {
                    if (!_CalendarConstructor.ContainsKey(validatorType))
                        _CalendarConstructor[validatorType] = validatorType.GetConstructor(new Type[] { typeof(IResourceManager), typeof(IICalendarCollection) });
                    ci = _CalendarConstructor[validatorType];
                    if (ci != null)
                        validator = ci.Invoke(new object[] { mgr, calendars }) as IValidator;
                }
            }

            return validator;
        }
Beispiel #20
0
    public void GetAllEvents()
    {
        List <CSVEvent> Events = new List <CSVEvent>();

        try
        {
            IICalendarCollection feed = iCalUtility.Deserialize(url);
            foreach (IEvent e in feed.SelectMany(e => e.Events))
            {
                CSVEvent csvEvent = new CSVEvent
                {
                    EventName    = e.Summary,
                    YearLevel    = e.Categories.FirstOrDefault(),
                    Cost         = e.Properties.Get <string>("X-COST"),
                    Location     = e.Location,
                    StartDate    = e.Start.Date,
                    FinishDate   = e.DTEnd.Date,
                    OtherDetails = e.Description
                };
                if (!String.IsNullOrEmpty(csvEvent.EventName))
                {
                    csvEvent.EventName = Encoding.UTF8.GetString(Encoding.Default.GetBytes(csvEvent.EventName)); // Fixes encoding issues
                }
                if (!String.IsNullOrEmpty(csvEvent.OtherDetails))
                {
                    csvEvent.OtherDetails = Encoding.UTF8.GetString(Encoding.Default.GetBytes(csvEvent.OtherDetails)); // Fixes encoding issues
                }
                if (e.Start.HasTime && !e.IsAllDay)
                {
                    csvEvent.StartTime = e.Start.Date.Add(e.Start.TimeOfDay);
                }

                if (e.End.HasTime)
                {
                    csvEvent.FinishTime = e.DTEnd.Date.Add(e.DTEnd.TimeOfDay);
                }

                int PlaceHolder; // Only used in the output of TryParse
                if (!String.IsNullOrEmpty(csvEvent.YearLevel))
                {
                    csvEvent.YearLevel = csvEvent.YearLevel.Replace("Year ", "").Replace("Whole School", "");
                }

                if (!int.TryParse(csvEvent.YearLevel, out PlaceHolder))
                {
                    csvEvent.YearLevel = String.Empty; // eDiary can only handle numbers, blank year level is treated as whole school
                }
                DateTime FirstDayOfYear = new DateTime(DateTime.Now.Year, 1, 1);
                if (csvEvent.StartDate > FirstDayOfYear) // Only get events from this year onwards to prevent massive files
                {
                    Events.Add(csvEvent);
                }
            }
        }
        catch (Exception ex)
        {
            using (StreamWriter writer = new StreamWriter(HttpContext.Current.Server.MapPath("~/log.txt"), true))
            {
                writer.WriteLine("Message :" + ex.Message + "\n" + Environment.NewLine + "StackTrace :" + ex.StackTrace +
                                 "" + Environment.NewLine + "Date :" + DateTime.Now.ToString());
                writer.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine);
            }
        }
        cc.Write(Events, HttpContext.Current.Server.MapPath("~/events.csv"), InputFileDescription);
        Clients.Caller.Download("events.csv");
    }
        /** <summary>
         * Given a URI/URL, we call iCalendar's LoadFromURI, select the first element in the return, then return true.
         * </summary>
         */
        public bool Load(Uri path)
        {
            iCalc = iCalendar.LoadFromUri(path);

            iCal = iCalc.FirstOrDefault();
            this.Uri = path;
            return true;
        }
 public DateTimeValuesValidator(IResourceManager mgr, IICalendarCollection calendars)
     : base(mgr)
 {
 }
 public ProdIDValidator(IResourceManager mgr, IICalendarCollection calendars)
     : base(mgr)
 {
     Calendars = calendars;
 }
 public static IValidator Create(Type validatorType, IResourceManager mgr, IICalendarCollection calendars)
 {
     return Create(validatorType, mgr, calendars, null);
 }
Beispiel #25
0
        static public IICalendarCollection LoadFromUri(Type iCalendarType, Uri uri, string username, string password, WebProxy proxy)
#endif
        {
            try
            {
                WebRequest request = WebRequest.Create(uri);

                if (username != null && password != null)
                {
                    request.Credentials = new System.Net.NetworkCredential(username, password);
                }

#if !SILVERLIGHT
                if (proxy != null)
                {
                    request.Proxy = proxy;
                }
#endif

                AutoResetEvent evt = new AutoResetEvent(false);

                string str = null;
                request.BeginGetResponse(new AsyncCallback(
                                             delegate(IAsyncResult result)
                {
                    Encoding e = Encoding.UTF8;

                    try
                    {
                        using (WebResponse resp = request.EndGetResponse(result))
                        {
                            // Try to determine the content encoding
                            try
                            {
                                List <string> keys = new List <string>(resp.Headers.AllKeys);
                                if (keys.Contains("Content-Encoding"))
                                {
                                    e = Encoding.GetEncoding(resp.Headers["Content-Encoding"]);
                                }
                            }
                            catch
                            {
                                // Fail gracefully back to UTF-8
                            }

                            using (Stream stream = resp.GetResponseStream())
                                using (StreamReader sr = new StreamReader(stream, e))
                                {
                                    str = sr.ReadToEnd();
                                }
                        }
                    }
                    finally
                    {
                        evt.Set();
                    }
                }
                                             ), null);

                evt.WaitOne();

                if (str != null)
                {
                    StringReader         reader     = new StringReader(str);
                    IICalendarCollection collection = LoadFromStream(reader);
                    reader.Dispose();
                    return(collection);
                }
                return(null);
            }
            catch (System.Net.WebException)
            {
                return(null);
            }
        }
 public EventValidation(IResourceManager mgr, string rule, IICalendarCollection calendars)
     : base(mgr)
 {
     Rule = rule;
     Calendars = calendars;
 }
Beispiel #27
0
        private void ImportEventsIntoExistingCalendar(IICalendarCollection collection, int calendar_id)
        {
            var cctrl  = new CalendarApiController();
            var ectrl  = new EventApiController();
            var rectrl = new REventApiController();

            //loop through calendar in collection
            foreach (var cal in collection)
            {
                //loop through events in calendar
                foreach (var e in cal.Events)
                {
                    //check if it is an reccuring event
                    if (e.RecurrenceRules.Count > 0)
                    {
                        var revent = new RecurringEvent()
                        {
                            allDay = e.IsAllDay, title = e.Summary, start = e.Start.Date, end = e.Start.Date, calendarId = calendar_id, categories = String.Join(",", e.Categories), Id = 0
                        };
                        revent.monthly_interval = (int)MonthlyIntervalEnum.First;
                        RecurrencePattern rp = (RecurrencePattern)e.RecurrenceRules[0];
                        switch (rp.Frequency)
                        {
                        case FrequencyType.Daily:
                        {
                            revent.frequency = (int)FrequencyTypeEnum.Daily;
                            break;
                        }

                        case FrequencyType.Monthly:
                        {
                            revent.frequency = (int)FrequencyTypeEnum.Monthly;
                            break;
                        }

                        case FrequencyType.Weekly:
                        {
                            revent.frequency = (int)FrequencyTypeEnum.Weekly;
                            break;
                        }

                        default:
                        {
                            revent.frequency = (int)FrequencyTypeEnum.Monthly;
                            break;
                        }
                        }
                        switch (e.Start.DayOfWeek)
                        {
                        case DayOfWeek.Monday: {
                            revent.day = (int)DayOfWeekEnum.Mon;
                            break;
                        }

                        case DayOfWeek.Tuesday:
                        {
                            revent.day = (int)DayOfWeekEnum.Tue;
                            break;
                        }

                        case DayOfWeek.Wednesday:
                        {
                            revent.day = (int)DayOfWeekEnum.Wed;
                            break;
                        }

                        case DayOfWeek.Thursday:
                        {
                            revent.day = (int)DayOfWeekEnum.Thu;
                            break;
                        }

                        case DayOfWeek.Friday:
                        {
                            revent.day = (int)DayOfWeekEnum.Fri;
                            break;
                        }

                        case DayOfWeek.Saturday:
                        {
                            revent.day = (int)DayOfWeekEnum.Sat;
                            break;
                        }

                        case DayOfWeek.Sunday:
                        {
                            revent.day = (int)DayOfWeekEnum.Sun;
                            break;
                        }
                        }
                        rectrl.PostSave(revent);
                    }
                    else
                    {
                        ectrl.PostSave(new EventCalendar.Core.Models.Event()
                        {
                            allDay = e.IsAllDay, calendarId = calendar_id, title = e.Summary, start = e.Start.Date, end = e.End.Date, Id = 0, categories = String.Join(",", e.Categories)
                        });
                    }
                }
            }
        }
        private void ImportEventsToNewCalendar(IICalendarCollection collection)
        {
            var cctrl = new CalendarApiController();
            var ectrl = new EventApiController();
            var rectrl = new REventApiController();            

            //loop through calendar in collection
            foreach (var cal in collection)
            {
                //Create the new calendar
                string name = "New Imported Calendar";
                if(cal.Properties["X-WR-CALNAME"] != null) {
                    if(!String.IsNullOrEmpty(cal.Properties["X-WR-CALNAME"].Value.ToString())) {
                        name = cal.Properties["X-WR-CALNAME"].Value.ToString();
                    }
                }
                var calendar = cctrl.PostSave(new ECalendar() { Id = 0, Calendarname = name, DisplayOnSite = false, IsGCal = false, GCalFeedUrl = "", ViewMode = "month", Color = "#000000", TextColor = "#FFFFFF" });
                //loop through events in calendar
                foreach (var e in cal.Events)
                {
                    //check if it is an reccuring event
                    if (e.RecurrenceRules.Count > 0)
                    {
                        var revent = new RecurringEvent() { allDay = e.IsAllDay, title = e.Summary, start = e.Start.Date, end = e.Start.Date, calendarId = calendar.Id, categories = String.Join(",", e.Categories), Id = 0 };
                        revent.monthly_interval = (int)MonthlyIntervalEnum.First;
                        RecurrencePattern rp = (RecurrencePattern)e.RecurrenceRules[0];
                        switch (rp.Frequency)
                        {
                            case FrequencyType.Daily:
                                {
                                    revent.frequency = (int)FrequencyTypeEnum.Daily;
                                    break;
                                }
                            case FrequencyType.Monthly:
                                {
                                    revent.frequency = (int)FrequencyTypeEnum.Monthly;
                                    break;
                                }
                            case FrequencyType.Weekly:
                                {
                                    revent.frequency = (int)FrequencyTypeEnum.Weekly;
                                    break;
                                }
                            default:
                                {
                                    revent.frequency = (int)FrequencyTypeEnum.Monthly;
                                    break;
                                }
                        }
                        switch (rp.ByDay[0].DayOfWeek)
                        {
                            case DayOfWeek.Monday:
                                {
                                    revent.day = (int)DayOfWeekEnum.Mon;
                                    break;
                                }
                            case DayOfWeek.Tuesday:
                                {
                                    revent.day = (int)DayOfWeekEnum.Tue;
                                    break;
                                }
                            case DayOfWeek.Wednesday:
                                {
                                    revent.day = (int)DayOfWeekEnum.Wed;
                                    break;
                                }
                            case DayOfWeek.Thursday:
                                {
                                    revent.day = (int)DayOfWeekEnum.Thu;
                                    break;
                                }
                            case DayOfWeek.Friday:
                                {
                                    revent.day = (int)DayOfWeekEnum.Fri;
                                    break;
                                }
                            case DayOfWeek.Saturday:
                                {
                                    revent.day = (int)DayOfWeekEnum.Sat;
                                    break;
                                }
                            case DayOfWeek.Sunday:
                                {
                                    revent.day = (int)DayOfWeekEnum.Sun;
                                    break;
                                }
                        }
                        rectrl.PostSave(revent);
                    }
                    else
                    {
                        ectrl.PostSave(new EventCalendar.Core.Models.Event() { allDay = e.IsAllDay, calendarId = calendar.Id, title = e.Summary, start = e.Start.Date, end = e.End.Date, Id = 0, categories = String.Join(",", e.Categories) });
                    }
                }
            }
        }
        /// <summary>
        ///     Executed before the message is saved
        /// </summary>
        /// <param name="message"></param>
        /// <param name="postSaveAction">if not null an action run after the save. This happens even if the save is cancelled.</param>
        /// <returns>
        ///     True if the save is to be cancelled
        /// </returns>
        public bool BeforeSave(ReceivedEmailMessage message, out Action postSaveAction)
        {
            postSaveAction = null;

            /////
            // Check the message.
            /////
            if (message == null)
            {
                return(false);
            }

            var iCalMessage = message.As <ReceivedICalEmailMessage>( );

            /////
            // Ensure the message is a received iCal email message.
            /////
            if (iCalMessage == null)
            {
                return(false);
            }

            /////
            // The iCalUpdate field was set by the iCalMailMesssageFormatter that was called as part
            // of the ProcessInboxes action.
            /////
            if (string.IsNullOrEmpty(iCalMessage.ICalUpdate))
            {
                return(false);
            }

            /////
            // Read the iCal update.
            /////
            using (var sr = new StringReader(iCalMessage.ICalUpdate))
            {
                /////
                // Deserialize the string into the iCal object model.
                /////
                IICalendarCollection iCalendarCollection = iCalendar.LoadFromStream(sr);

                if (iCalendarCollection == null)
                {
                    return(false);
                }

                /////
                // Get the first calendar.
                /////
                IICalendar calendar = iCalendarCollection.FirstOrDefault( );

                if (calendar == null || calendar.Events == null)
                {
                    return(false);
                }

                /////
                // Get the first calendar event.
                /////
                IEvent calendarEvent = calendar.Events.FirstOrDefault( );

                if (calendarEvent == null)
                {
                    return(false);
                }

                /////
                // Make sure the calendar events UID is set.
                /////
                if (string.IsNullOrEmpty(calendarEvent.Uid))
                {
                    return(false);
                }

                EventEmail  eventEntity = null;
                Appointment appointment = null;

                /////
                // Find all sent iCal UID containers that correlate to the received calendar events UID.
                /////
                IEnumerable <ICalUidContainer> iCalUidContainers = Entity.GetByField <ICalUidContainer>(calendarEvent.Uid, ICalUidContainer.ICalUid_Field);

                if (iCalUidContainers != null)
                {
                    /////
                    // Get the first sent message.
                    /////
                    ICalUidContainer iCalUidContainer = iCalUidContainers.FirstOrDefault( );

                    if (iCalUidContainer != null && iCalUidContainer.CalendarEventEmail != null)
                    {
                        /////
                        // Get the original event email object that was used to create the sent iCal Email Message.
                        /////
                        eventEntity = iCalUidContainer.CalendarEventEmail.AsWritable <EventEmail>( );
                    }
                }

                bool modificationsMade = false;

                if (eventEntity == null)
                {
                    /////
                    // No existing event email so this is a new request.
                    /////
                    EntityRef type = GetEventCreationType(message);

                    eventEntity = type != null?Entity.Create(type).As <EventEmail>( ) : new EventEmail( );

                    appointment = Entity.Create <Appointment>();
                    eventEntity.EventEmailAppt = appointment;

                    modificationsMade = true;

                    eventEntity.Name = calendarEvent.Summary;

                    var calUidContainer = new ICalUidContainer
                    {
                        ICalUid = calendarEvent.Uid
                    };

                    eventEntity.CalendarId = calUidContainer;

                    string creatorEmailAddress = GetEmailAddress(message.EmFrom);

                    if (creatorEmailAddress != null)
                    {
                        EmailContact creatorEmailContact = FindEmailContact(creatorEmailAddress);

                        if (creatorEmailContact == null)
                        {
                            var mailAddress = new MailAddress(message.EmFrom);

                            creatorEmailContact = CreateEmailContact(creatorEmailAddress, mailAddress.DisplayName ?? creatorEmailAddress);
                        }

                        eventEntity.EventEmailCreator = creatorEmailContact;
                    }

                    foreach (IAttendee attendee in calendarEvent.Attendees)
                    {
                        string emailAddress = GetEmailAddress(attendee.Value.ToString( ));

                        if (emailAddress != null)
                        {
                            EmailContact emailContact = FindEmailContact(emailAddress);

                            if (emailContact == null)
                            {
                                CreateEmailContact(emailAddress, attendee.CommonName);
                            }

                            appointment.EventEmailAttendees.Add(emailContact.EmailContactOwner);
                        }
                    }

                    CreateAndSendAcceptance(calendar, iCalMessage, eventEntity);
                }
                else
                {
                    appointment = eventEntity.EventEmailAppt;

                    if (calendar.Method == Methods.Publish || calendar.Method == Methods.Request)
                    {
                        /////
                        // A REQUEST or PUBLISH means a new event arriving in the system.
                        /////
                        CreateAndSendAcceptance(calendar, iCalMessage, eventEntity);
                    }
                }


                eventEntity.ReceivedEmailMessages.Add(iCalMessage);


                /////
                // Start time.
                /////
                if (calendarEvent.Start != null)
                {
                    DateTime utcTime = calendarEvent.Start.Utc;

                    if (!Equals(utcTime, appointment.EventStart))
                    {
                        appointment.EventStart = utcTime;
                        modificationsMade      = true;
                    }
                }

                /////
                // End time.
                /////
                if (calendarEvent.End != null)
                {
                    DateTime utcTime = calendarEvent.End.Utc;

                    if (!Equals(utcTime, appointment.EventEnd))
                    {
                        appointment.EventEnd = utcTime;
                        modificationsMade    = true;
                    }
                }

                /////
                // All Day Event.
                /////
                if (appointment.EventIsAllDay == null || !Equals(calendarEvent.IsAllDay, appointment.EventIsAllDay.Value))
                {
                    appointment.EventIsAllDay = calendarEvent.IsAllDay;
                    modificationsMade         = true;
                }

                /////
                // Location.
                /////
                if (calendarEvent.Location != null)
                {
                    if (!Equals(calendarEvent.Location, appointment.EventLocation))
                    {
                        appointment.EventLocation = calendarEvent.Location;
                        modificationsMade         = true;
                    }
                }

                /////
                // Location.
                /////
                if (eventEntity.EventEmailAppt.EventEmailPriority == null || !Equals(calendarEvent.Priority, eventEntity.EventEmailAppt.EventEmailPriority))
                {
                    string priorityAlias;

                    if (calendarEvent.Priority <= 0)
                    {
                        /////
                        // Undefined.
                        /////
                        priorityAlias = null;
                    }
                    else if (calendarEvent.Priority <= 4)
                    {
                        /////
                        // High priority.
                        /////
                        priorityAlias = "core:highPriority";
                    }
                    else if (calendarEvent.Priority == 5)
                    {
                        /////
                        // Normal priority.
                        /////
                        priorityAlias = "core:normalPriority";
                    }
                    else if (calendarEvent.Priority <= 9)
                    {
                        /////
                        // Low priority.
                        /////
                        priorityAlias = "core:lowPriority";
                    }
                    else
                    {
                        /////
                        // Invalid priority.
                        /////
                        priorityAlias = null;
                    }

                    eventEntity.EventEmailAppt.EventEmailPriority = priorityAlias != null?Entity.Get <EventEmailPriorityEnum>(priorityAlias) : null;

                    modificationsMade = true;
                }

                /////
                // Status.
                /////
                string statusAlias = null;

                switch (calendarEvent.Status)
                {
                case EventStatus.Cancelled:
                    statusAlias = "core:eventStatusCancelled";
                    break;

                case EventStatus.Confirmed:
                    statusAlias = "core:eventStatusConfirmed";
                    break;

                case EventStatus.Tentative:
                    statusAlias = "core:eventStatusTentative";
                    break;
                }

                if (!string.IsNullOrEmpty(statusAlias))
                {
                    if (appointment.EventStatus == null || appointment.EventStatus.Alias != statusAlias)
                    {
                        appointment.EventStatus = Entity.Get <EventStatusEnum>(statusAlias);
                        modificationsMade       = true;
                    }
                }

                if (modificationsMade)
                {
                    CustomContext cc = null;

                    try
                    {
                        string timeZone = null;

                        if (eventEntity != null)
                        {
                            /////
                            // Find all sent iCal Email Messages that correlate to the received calendar events UID.
                            /////
                            IEnumerable <SentICalEmailMessage> sentICalEmailMessages = eventEntity.SentEmailMessages;

                            if (sentICalEmailMessages != null)
                            {
                                SentICalEmailMessage sentICalEmailMessage = sentICalEmailMessages.FirstOrDefault(sent => sent.ICalTimeZone != null);

                                if (sentICalEmailMessage != null)
                                {
                                    timeZone = sentICalEmailMessage.ICalTimeZone;
                                }
                            }
                        }

                        if (string.IsNullOrEmpty(timeZone))
                        {
                            if (calendar.TimeZones != null)
                            {
                                ITimeZone calendarTimeZone = calendar.TimeZones.FirstOrDefault( );

                                if (calendarTimeZone != null)
                                {
                                    timeZone = calendarTimeZone.TzId;
                                }
                            }
                        }

                        if (!string.IsNullOrEmpty(timeZone))
                        {
                            /////
                            // Set up a custom context just for the duration of this call.
                            /////
                            RequestContext currentRequestContext = RequestContext.GetContext( );

                            var data = new RequestContextData(currentRequestContext)
                            {
                                TimeZone = timeZone
                            };

                            cc = new CustomContext(data);
                        }

                        eventEntity.Save( );
                    }
                    finally
                    {
                        /////
                        // Ensure the custom context is disposed.
                        /////
                        if (cc != null)
                        {
                            cc.Dispose( );
                        }
                    }
                }
            }

            return(false);
        }
Beispiel #30
0
        private void ImportEventsToNewCalendar(IICalendarCollection collection)
        {
            var cctrl  = new CalendarApiController();
            var ectrl  = new EventApiController();
            var rectrl = new REventApiController();

            //loop through calendar in collection
            foreach (var cal in collection)
            {
                //Create the new calendar
                string name = "New Imported Calendar";
                if (cal.Properties["X-WR-CALNAME"] != null)
                {
                    if (!String.IsNullOrEmpty(cal.Properties["X-WR-CALNAME"].Value.ToString()))
                    {
                        name = cal.Properties["X-WR-CALNAME"].Value.ToString();
                    }
                }
                var calendar = cctrl.PostSave(new ECalendar()
                {
                    Id = 0, Calendarname = name, DisplayOnSite = false, IsGCal = false, GCalFeedUrl = "", ViewMode = "month", Color = "#000000", TextColor = "#FFFFFF"
                });
                //loop through events in calendar
                foreach (var e in cal.Events)
                {
                    //check if it is an reccuring event
                    if (e.RecurrenceRules.Count > 0)
                    {
                        var revent = new RecurringEvent()
                        {
                            allDay = e.IsAllDay, title = e.Summary, start = e.Start.Date, end = e.Start.Date, calendarId = calendar.Id, categories = String.Join(",", e.Categories), Id = 0
                        };
                        revent.monthly_interval = (int)MonthlyIntervalEnum.First;
                        RecurrencePattern rp = (RecurrencePattern)e.RecurrenceRules[0];
                        switch (rp.Frequency)
                        {
                        case FrequencyType.Daily:
                        {
                            revent.frequency = (int)FrequencyTypeEnum.Daily;
                            break;
                        }

                        case FrequencyType.Monthly:
                        {
                            revent.frequency = (int)FrequencyTypeEnum.Monthly;
                            break;
                        }

                        case FrequencyType.Weekly:
                        {
                            revent.frequency = (int)FrequencyTypeEnum.Weekly;
                            break;
                        }

                        default:
                        {
                            revent.frequency = (int)FrequencyTypeEnum.Monthly;
                            break;
                        }
                        }
                        switch (rp.ByDay[0].DayOfWeek)
                        {
                        case DayOfWeek.Monday:
                        {
                            revent.day = (int)DayOfWeekEnum.Mon;
                            break;
                        }

                        case DayOfWeek.Tuesday:
                        {
                            revent.day = (int)DayOfWeekEnum.Tue;
                            break;
                        }

                        case DayOfWeek.Wednesday:
                        {
                            revent.day = (int)DayOfWeekEnum.Wed;
                            break;
                        }

                        case DayOfWeek.Thursday:
                        {
                            revent.day = (int)DayOfWeekEnum.Thu;
                            break;
                        }

                        case DayOfWeek.Friday:
                        {
                            revent.day = (int)DayOfWeekEnum.Fri;
                            break;
                        }

                        case DayOfWeek.Saturday:
                        {
                            revent.day = (int)DayOfWeekEnum.Sat;
                            break;
                        }

                        case DayOfWeek.Sunday:
                        {
                            revent.day = (int)DayOfWeekEnum.Sun;
                            break;
                        }
                        }
                        rectrl.PostSave(revent);
                    }
                    else
                    {
                        ectrl.PostSave(new EventCalendar.Core.Models.Event()
                        {
                            allDay = e.IsAllDay, calendarId = calendar.Id, title = e.Summary, start = e.Start.Date, end = e.End.Date, Id = 0, categories = String.Join(",", e.Categories)
                        });
                    }
                }
            }
        }
        public ActionResult ImportEvents(HttpPostedFileBase file, string from = "", string to = "", bool showEndDate = false)
        {
            int courseId = ActiveCourseUser.AbstractCourseID;

            DateTime fromDate  = new DateTime();
            DateTime toDate    = new DateTime();
            bool     fromParse = false;
            bool     toParse   = false;

            fromParse = DateTime.TryParse(from, out fromDate);
            toParse   = DateTime.TryParse(to, out toDate);

            IICalendarCollection calendars = iCalendar.LoadFromStream(new StreamReader(file.InputStream));

            IList <Occurrence> occurrences = fromParse && toParse?calendars.GetOccurrences(fromDate, toDate) : calendars.GetOccurrences(DateTime.Today.AddYears(-1), DateTime.Today.AddYears(1));  //if no range specified, arbitrarily choose +/- 1 year max future/past range

            List <OSBLE.Models.HomePage.Event> events = new List <OSBLE.Models.HomePage.Event>();
            List <OSBLE.Models.HomePage.Event> nullDescriptionEvents = new List <OSBLE.Models.HomePage.Event>();

            foreach (Occurrence occurrence in occurrences)
            {
                IRecurringComponent component = occurrence.Source as IRecurringComponent;

                OSBLE.Models.HomePage.Event newEvent = new OSBLE.Models.HomePage.Event
                {
                    Poster    = ActiveCourseUser,
                    Approved  = true,
                    StartDate = DateTime.SpecifyKind(occurrence.Period.StartTime.Local.Date, DateTimeKind.Unspecified).CourseToUTC(courseId),
                    EndDate   = showEndDate ?
                                (occurrence.Period.EndTime.IsUniversalTime ?
                                 DateTime.SpecifyKind(occurrence.Period.EndTime.Local.Date, DateTimeKind.Unspecified) :
                                 DateTime.SpecifyKind(occurrence.Period.EndTime.Local.Date, DateTimeKind.Unspecified).CourseToUTC(courseId)) :
                                (DateTime?)null,
                    StartTime = occurrence.Period.StartTime.IsUniversalTime ?
                                DateTime.SpecifyKind(occurrence.Period.StartTime.Local, DateTimeKind.Unspecified) :
                                DateTime.SpecifyKind(occurrence.Period.StartTime.Local, DateTimeKind.Unspecified).CourseToUTC(courseId),
                    EndTime = occurrence.Period.EndTime.IsUniversalTime ?
                              DateTime.SpecifyKind(occurrence.Period.EndTime.Local, DateTimeKind.Unspecified) :
                              DateTime.SpecifyKind(occurrence.Period.EndTime.Local, DateTimeKind.Unspecified).CourseToUTC(courseId),
                    Description = component.Description,
                    Title       = String.IsNullOrEmpty(((DDay.iCal.Event)component).Location) ?
                                  component.Summary :
                                  component.Summary + " - " + ((DDay.iCal.Event)component).Location,
                };

                if (String.IsNullOrEmpty(newEvent.Description))
                {
                    nullDescriptionEvents.Add(newEvent);
                }
                else
                {
                    events.Add(newEvent);
                }
            }

            //add non duplicate events with null description. doing this because it seems google saves an additional event when you
            //edit an event in a recurring series to add more description
            foreach (var nullDescriptionEvent in nullDescriptionEvents)
            {
                if (events.Where(e => e.StartDate == nullDescriptionEvent.StartDate &&
                                 e.EndDate == nullDescriptionEvent.EndDate &&
                                 e.StartTime == nullDescriptionEvent.StartTime &&
                                 e.EndTime == nullDescriptionEvent.EndTime).Count() == 0)
                {
                    events.Add(nullDescriptionEvent);
                }
            }

            CreateEvents(events);

            return(RedirectToAction("Index", "Event"));
        }
 public ComponentValidator(IResourceManager mgr, IICalendarCollection calendars)
     : base(mgr, calendars)
 {
 }
 public EventClassPropertyValidator(IResourceManager mgr, IICalendarCollection calendars)
     : base(mgr, "eventClassProperty", calendars)
 {
     Calendars = calendars;
 }
Beispiel #34
0
		public SEvent[] GetEvents(IICalendarCollection calCollection)
		{
			if (calCollection == null) return null;
			return GetEvents(calCollection.ToArray());
		}
        private void ImportEventsIntoExistingCalendar(IICalendarCollection collection, int calendar_id)
        {
            var cctrl = new CalendarApiController();
            var ectrl = new EventApiController();
            var rectrl = new REventApiController();

            //loop through calendar in collection
            foreach (var cal in collection)
            {
                //loop through events in calendar
                foreach (var e in cal.Events)
                {
                    //check if it is an reccuring event
                    if (e.RecurrenceRules.Count > 0)
                    {
                        var revent = new RecurringEvent(){ allDay = e.IsAllDay, title = e.Summary, start = e.Start.Date, end = e.Start.Date, calendarId = calendar_id, categories = String.Join(",", e.Categories), Id = 0};
                        revent.monthly_interval = (int)MonthlyIntervalEnum.First;
                        RecurrencePattern rp = (RecurrencePattern)e.RecurrenceRules[0];
                        switch (rp.Frequency)
                        {
                            case FrequencyType.Daily:
                                {
                                    revent.frequency = (int)FrequencyTypeEnum.Daily;
                                    break;
                                }
                            case FrequencyType.Monthly:
                                {
                                    revent.frequency = (int)FrequencyTypeEnum.Monthly;
                                    break;
                                }
                            case FrequencyType.Weekly:
                                {
                                    revent.frequency = (int)FrequencyTypeEnum.Weekly;
                                    break;
                                }
                            default:
                                {
                                    revent.frequency = (int)FrequencyTypeEnum.Monthly;
                                    break;
                                }
                        }
                        switch(e.Start.DayOfWeek) {
                            case DayOfWeek.Monday: {
                                revent.day = (int)DayOfWeekEnum.Mon;
                                break;
                            }
                            case DayOfWeek.Tuesday:
                                {
                                    revent.day = (int)DayOfWeekEnum.Tue;
                                    break;
                                }
                            case DayOfWeek.Wednesday:
                                {
                                    revent.day = (int)DayOfWeekEnum.Wed;
                                    break;
                                }
                            case DayOfWeek.Thursday:
                                {
                                    revent.day = (int)DayOfWeekEnum.Thu;
                                    break;
                                }
                            case DayOfWeek.Friday:
                                {
                                    revent.day = (int)DayOfWeekEnum.Fri;
                                    break;
                                }
                            case DayOfWeek.Saturday:
                                {
                                    revent.day = (int)DayOfWeekEnum.Sat;
                                    break;
                                }
                            case DayOfWeek.Sunday:
                                {
                                    revent.day = (int)DayOfWeekEnum.Sun;
                                    break;
                                }
                        }
                        rectrl.PostSave(revent);
                    }
                    else
                    {
                        ectrl.PostSave(new EventCalendar.Core.Models.Event() { allDay = e.IsAllDay, calendarId = calendar_id, title = e.Summary, start = e.Start.Date, end = e.End.Date, Id = 0, categories = String.Join(",", e.Categories) });
                    }
                }
            }
        }
Beispiel #36
0
        /// <summary>
        ///     Gets the Ical update.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="receivedICalEmailMessage">The received I cal email message.</param>
        /// <param name="iCal">The i cal.</param>
        /// <returns></returns>
        private static MailMessageFormatterResult GetICalUpdate(MailMessage message, ReceivedICalEmailMessage receivedICalEmailMessage, out string iCal)
        {
            iCal = null;

            if (message == null)
            {
                return(MailMessageFormatterResult.Skip);
            }

            try
            {
                var attachableItems = new List <AttachmentBase>( );

                attachableItems.AddRange(message.AlternateViews);
                attachableItems.AddRange(message.Attachments);

                /////
                // Locate a view that contains a calendar attachment.
                /////
                foreach (AttachmentBase attachment in attachableItems)
                {
                    if (attachment.ContentType.MediaType == "text/calendar")
                    {
                        /////
                        // Deserialize the iCalendar attachment.
                        /////
                        IICalendarCollection iCalendarCollection = iCalendar.LoadFromStream(attachment.ContentStream);

                        if (iCalendarCollection != null)
                        {
                            IICalendar calendar = iCalendarCollection.FirstOrDefault( );

                            if (calendar != null)
                            {
                                if (calendar.Method == Methods.Reply)
                                {
                                    IEvent calendarEvent = calendar.Events.FirstOrDefault( );

                                    if (calendarEvent != null && !string.IsNullOrEmpty(calendarEvent.Uid))
                                    {
                                        /////
                                        // Find all iCal UID containers that correlate to the received calendar events UID.
                                        /////
                                        IEnumerable <ICalUidContainer> iCalUidContainers = Entity.GetByField <ICalUidContainer>(calendarEvent.Uid, ICalUidContainer.ICalUid_Field);

                                        if (iCalUidContainers != null)
                                        {
                                            /////
                                            // Get the first iCal UID container.
                                            /////
                                            ICalUidContainer iCalUidContainer = iCalUidContainers.FirstOrDefault( );

                                            if (iCalUidContainer != null && iCalUidContainer.CalendarEventEmail != null)
                                            {
                                                /////
                                                // Get the original event email object that was used to calendar UID container.
                                                /////
                                                EventEmail eventEntity = iCalUidContainer.CalendarEventEmail;

                                                if (eventEntity != null)
                                                {
                                                    // ***************
                                                    // This needs to be fixed as part of dealing with replies from ical requests. The rel on a rel needs to be turned into something else.
                                                    // ***************
                                                    //IEntityRelationship<EventEmailAttendees, EmailContact> attendeeRelationshipInstance = FindAttendeeRelationshipInstance( eventEntity, message.From.Address.ToLowerInvariant( ) );

                                                    //if ( attendeeRelationshipInstance != null )
                                                    //{
                                                    //    Attendee attendee = FindICalAttendee( calendarEvent, message.From.Address.ToLowerInvariant( ) );

                                                    //    if ( attendee != null )
                                                    //    {
                                                    //        var eventEmailAttendees = attendeeRelationshipInstance.Instance.AsWritable<EventEmailAttendees>( );

                                                    //        switch ( attendee.ParticipationStatus )
                                                    //        {
                                                    //            case ParticipationStatus.Accepted:
                                                    //                eventEmailAttendees.AttendeeStatus_Enum = AttendeeStatusEnum_Enumeration.AttendeeStatusAccepted;
                                                    //                break;
                                                    //            case ParticipationStatus.Declined:
                                                    //                eventEmailAttendees.AttendeeStatus_Enum = AttendeeStatusEnum_Enumeration.AttendeeStatusDeclined;
                                                    //                break;
                                                    //            case ParticipationStatus.Delegated:
                                                    //                eventEmailAttendees.AttendeeStatus_Enum = AttendeeStatusEnum_Enumeration.AttendeeStatusDelegated;
                                                    //                break;
                                                    //            case ParticipationStatus.NeedsAction:
                                                    //                eventEmailAttendees.AttendeeStatus_Enum = AttendeeStatusEnum_Enumeration.AttendeeStatusNeedsAction;
                                                    //                break;
                                                    //            case ParticipationStatus.Tentative:
                                                    //                eventEmailAttendees.AttendeeStatus_Enum = AttendeeStatusEnum_Enumeration.AttendeeStatusTentative;
                                                    //                break;
                                                    //        }

                                                    //        eventEmailAttendees.Save( );
                                                    //    }
                                                    //}

                                                    //*************

                                                    receivedICalEmailMessage.CreatedEventEmail = eventEntity;

                                                    /////
                                                    // Save the message since the process inbox action will discard it.
                                                    /////
                                                    receivedICalEmailMessage.Save( );
                                                }
                                            }
                                        }
                                    }

                                    return(MailMessageFormatterResult.Reject);
                                }

                                /////
                                // Serialize the iCalendar to a string for storage.
                                /////
                                var serializer = new iCalendarSerializer( );

                                iCal = serializer.SerializeToString(calendar);

                                return(MailMessageFormatterResult.Ok);
                            }
                        }

                        break;
                    }
                }
            }
            catch (Exception exc)
            {
                EventLog.Application.WriteError("Failed to process email iCal attachment. " + exc);

                return(MailMessageFormatterResult.Error);
            }

            return(MailMessageFormatterResult.Skip);
        }
 public VersionValidator(IResourceManager mgr, string icalText, IICalendarCollection calendars)
     : base(mgr)
 {
     iCalText = icalText;
     Calendars = calendars;
 }
Beispiel #38
0
        // ---------- METHODS ----------

        /// <summary>
        /// Gets a calendar from the provider.
        /// </summary>
        /// <param name="name">The name of the calendar to retrieve.</param>
        /// <param name="startDate">Events starting on or after this date will be included in the list returned.</param>
        /// <param name="endDate">Events starting on or before this date will be included in the list returned.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if a name that is empty, null,
        /// or full of whitespace is provided.</exception>
        /// <returns>The calendar with the supplied name, or null if a calendar of that name does not exist
        /// or could not be retrieved.</returns>
        /// <remarks>This method only returns the first calendar in iCalendar files that contain multiple calendars.</remarks>
        override public Calendar GetCalendar(string name, DateTime startDate, DateTime endDate)
        {
            // Check that a name was provided.
            if (!string.IsNullOrWhiteSpace(name))
            {
                // A name was provided.
                // Check whether the name exists in the list of available calendars.
                if (calendars.ContainsKey(name))
                {
                    // The calendar is available.
                    // Get the calendar from the file.
                    IICalendarCollection calendarCollection = DDay.iCal.iCalendar.LoadFromUri(calendars[name]);
                    if (calendarCollection.Count > 0)
                    {
                        // The iCalendar file contains a calendar, get the first one.
                        IICalendar iCalCalendar = calendarCollection[0];

                        // Create the calendar object from the file.
                        Calendar calendar = new Calendar {
                            Name = name, Description = ""
                        };

                        // Get the events associated with the calendar.
                        foreach (IEvent iCalEvent in iCalCalendar.Events)
                        {
                            // Create an event for the calendar.
                            Event calendarEvent = new Event
                            {
                                // Populate the event with data from the iCalendar event.
                                Title       = iCalEvent.Summary,
                                Description = iCalEvent.Description,
                                Location    = iCalEvent.Location,
                                LocationUrl = null,
                                Canceled    = iCalEvent.Status.HasFlag(EventStatus.Cancelled),
                                NoEndTime   = false
                            };

                            // Set the event's priorty based upon the thresholds defined in the iCalendar standard.
                            if (iCalEvent.Priority == PRIORITY_THRESHOLD_UNDEFINED)
                            {
                                // A priority is not defined for this event.
                                // Default it to Medium.
                                calendarEvent.Priority = Event.PriorityLevels.Medium;
                            }
                            else if (iCalEvent.Priority <= PRIORITY_THRESHOLD_HIGH)
                            {
                                calendarEvent.Priority = Event.PriorityLevels.High;
                            }
                            else if (iCalEvent.Priority <= PRIORITY_THRESHOLD_MEDIUM)
                            {
                                calendarEvent.Priority = Event.PriorityLevels.Medium;
                            }
                            else
                            {
                                calendarEvent.Priority = Event.PriorityLevels.Low;
                            }

                            calendarEvent.StartDate   = iCalEvent.Start.Value;
                            calendarEvent.EndDate     = iCalEvent.End.Value;
                            calendarEvent.AllDayEvent = iCalEvent.IsAllDay;
                            if (iCalEvent.Contacts != null && iCalEvent.Contacts.Count > 0)
                            {
                                // Only grab the first contact. (Some other calendars don't support multiple contacts.)
                                calendarEvent.ContactName = iCalEvent.Contacts[0];
                            }
                            calendarEvent.ContactPhone        = null;
                            calendarEvent.ContactEmail        = null;
                            calendarEvent.OnMultipleCalendars = false;
                            if (iCalEvent.RecurrenceDates != null && iCalEvent.RecurrenceDates.Count > 0)
                            {
                                calendarEvent.Reoccurring = true;
                            }
                            else
                            {
                                calendarEvent.Reoccurring = false;
                            }
                            if (iCalEvent.LastModified != null)
                            {
                                calendarEvent.LastUpdated = iCalEvent.LastModified.Value;
                            }
                            calendarEvent.LastUpdatedBy = null;
                            if (iCalEvent.LastModified != null)
                            {
                                calendarEvent.DetailsLastUpdated = iCalEvent.LastModified.Value;
                            }
                            calendarEvent.DetailsLastUpdatedBy = null;

                            // Add the events to the list of of events in the calendar.
                            calendar.Events.Add(calendarEvent);
                        }

                        // Return the initialized calendar.
                        return(calendar);
                    }
                    else
                    {
                        // The iCalendar file does not contain any calendars.
                        return(null);
                    }
                }
                else
                {
                    // The calendar doesn't exist.
                    return(null);
                }
            }
            else
            {
                // A name was not provided.
                throw new ArgumentNullException("name");
            }
        }
 public UnknownValueTypeParameterValidator(IResourceManager mgr, IICalendarCollection calendars)
     : base(mgr, calendars)
 {
 }
 public EventRRulePropertyValidator(IResourceManager mgr, IICalendarCollection calendars)
     : base(mgr, "eventRRuleProperty", calendars)
 {
 }
Beispiel #41
0
 public IEnumerable<IEvent> LoadEvents(IICalendarCollection calendars, DateTime start, DateTime? end)
 {
     if (end.HasValue)
         return calendars[0].Events.Where(x => x.Start.Local >= start && x.End.Local <= end.Value).OrderBy(y => y.Start);
     return calendars[0].Events.Where(x => x.Start.Local >= start).OrderBy(y => y.Start);
 }
 public InlineBinaryContentValidator(IResourceManager mgr, IICalendarCollection calendars)
     : base(mgr)
 {
     Calendars = calendars;
 }
 public CalendarObjectValidation(IResourceManager mgr, IICalendarCollection calendars)
     : base(mgr)
 {
     Calendars = calendars;
 }