Inheritance: RecurringComponent, IEvent
Beispiel #1
0
        public override void ExecuteResult(ControllerContext context)
        {
            var calendar = new iCalendar();

            calendar.AddProperty("X-WR-CALDESC", _name);
            calendar.AddProperty("X-WR-CALNAME", _name);

            foreach (var e in _events)
            {
                var calendarEvent = new DDay.iCal.Event {
                    Description = e.Description,
                    DTStamp     = new iCalDateTime(e.DateStart),
                    DTStart     = new iCalDateTime(e.DateStart),
                    IsAllDay    = true,
                    Location    = e.Location,
                    Summary     = e.Summary,
                    Url         = new Uri(e.Url)
                };

                calendar.Events.Add(calendarEvent);
            }

            var s = new iCalendarSerializer();

            context.HttpContext.Response.ContentType = "text/calendar";
            context.HttpContext.Response.Write(s.SerializeToString(calendar));
            context.HttpContext.Response.End();
        }
Beispiel #2
0
        public static void TestDDayCalendarWriter()
        {
            Console.WriteLine("Serializing using DDayCalendarWriter");

            DateTime startTime = DateTime.Now;

            using (var iCal = new iCalendar())
            {
                iCal.AddLocalTimeZone();
                iCal.AddProperty("X-WR-CALNAME", "CalendarName");

                using (var stream = new StreamWriter("test2.ical"))
                {
                    using (var writer = new DDayCalendarWriter(iCal, stream))
                    {
                        for (int count = 0; count < 100000; count++)
                        {
                            var evnt = new Event {Summary = "Event " + count};
                            writer.Write(evnt);
                        }
                    }
                }
            }
            Console.WriteLine("Done: " + (DateTime.Now - startTime));
        }
Beispiel #3
0
        /// <summary>
        /// Updates the help text.
        /// </summary>
        private void UpdateHelpText()
        {
            hbSchedulePreview.Text = "<div style='white-space: pre' Font-Names='Consolas' Font-Size='9'>" + sbSchedule.iCalendarContent + "</div>";

            iCalendar calendar = iCalendar.LoadFromStream(new StringReader(sbSchedule.iCalendarContent)).First() as iCalendar;

            DDay.iCal.Event calendarEvent = calendar.Events[0] as Event;

            if (calendarEvent.DTStart != null)
            {
                List <Occurrence> nextOccurrences = calendar.GetOccurrences(DateTime.Now.Date, DateTime.Now.Date.AddYears(1)).Take(26).ToList();

                string listHtml = "<hr /><span>Occurrences Preview</span><ul>";
                foreach (var occurrence in nextOccurrences)
                {
                    if (occurrence.Period.StartTime.Value.Date.Equals(occurrence.Period.EndTime.Value.Date))
                    {
                        listHtml += string.Format("<li>{0} - {1} to {2} ( {3} hours) </li>", occurrence.Period.StartTime.Value.Date.ToShortDateString(), occurrence.Period.StartTime.Value.TimeOfDay.ToTimeString(), occurrence.Period.EndTime.Value.TimeOfDay.ToTimeString(), occurrence.Period.Duration.TotalHours.ToString("#0.00"));
                    }
                    else
                    {
                        listHtml += string.Format("<li>{0} to {1} ( {2} hours) </li>", occurrence.Period.StartTime.Value.ToString("g"), occurrence.Period.EndTime.Value.ToString("g"), occurrence.Period.Duration.TotalHours.ToString("#0.00"));
                    }
                }

                listHtml += string.Format("<li>{0}</li>", "...");
                listHtml += "</ul>";

                hbSchedulePreview.Text += listHtml;
            }
        }
Beispiel #4
0
        public override void ExecuteResult(ControllerContext context)
        {
            var calendar = new iCalendar();
            calendar.AddProperty("X-WR-CALDESC", _name);
            calendar.AddProperty("X-WR-CALNAME", _name);

            foreach (var e in _events) {
                var calendarEvent = new DDay.iCal.Event {
                    Description = e.Description,
                    DTEnd = new iCalDateTime(e.DateEnd),
                    DTStamp = new iCalDateTime(e.DateStart),
                    DTStart = new iCalDateTime(e.DateStart),
                    Location = e.Location,
                    Summary = e.Summary,
                    Url = new Uri(e.Url)
                };

                calendar.Events.Add(calendarEvent);
            }

            var s = new iCalendarSerializer();
            context.HttpContext.Response.ContentType = "text/calendar";
            context.HttpContext.Response.Write(s.SerializeToString(calendar));
            context.HttpContext.Response.End();
        }
Beispiel #5
0
 /// <summary>
 /// Gets the occurrences.
 /// </summary>
 /// <param name="icalEvent">The ical event.</param>
 /// <param name="startTime">The start time.</param>
 /// <param name="endTime">The end time.</param>
 /// <returns></returns>
 public static IList <Occurrence> GetOccurrences(DDay.iCal.Event icalEvent, DateTime startTime, DateTime endTime)
 {
     lock (ScheduleICalHelper._initLock)
     {
         return(icalEvent.GetOccurrences(startTime, endTime));
     }
 }
        /// <summary>
        /// Updates the help text.
        /// </summary>
        private void UpdateHelpText()
        {
            var fakeSchedule = new Rock.Model.Schedule();

            fakeSchedule.iCalendarContent = sbSchedule.iCalendarContent;
            sbSchedule.ToolTip            = fakeSchedule.ToFriendlyScheduleText();

            hbSchedulePreview.Text = @"<strong>iCalendar Content</strong>
<div style='white-space: pre' Font-Names='Consolas' Font-Size='9'><br />" + sbSchedule.iCalendarContent + "</div>";

            iCalendar calendar = iCalendar.LoadFromStream(new StringReader(sbSchedule.iCalendarContent)).First() as iCalendar;

            DDay.iCal.Event calendarEvent = calendar.Events[0] as Event;

            if (calendarEvent.DTStart != null)
            {
                List <Occurrence> nextOccurrences = calendar.GetOccurrences(RockDateTime.Now, RockDateTime.Now.AddYears(1)).Take(26).ToList();

                string listHtml = "<hr /><strong>Occurrences Preview</strong><ul>";
                foreach (var occurrence in nextOccurrences)
                {
                    listHtml += "<li>" + GetOccurrenceText(occurrence) + "</li>";
                }

                listHtml += string.Format("<li>{0}</li>", "...");
                listHtml += "</ul>";

                hbSchedulePreview.Text += listHtml;
            }
        }
Beispiel #7
0
        public void MaybeApplyCatmapAddsExpectedCats()            // any matching category should expand via the map(without removing the matched category)
        {
            var test_feedurl    = "test_feedurl";
            var collector_keene = new Collector(new Calinfo("elmcity"), settings);

            collector_keene.per_feed_catmaps[test_feedurl] = new Dictionary <string, string>()
            {
                { "a", "l,M,n,O,p" },                           // this will map
                { "z", "q" }                                    // this won't
            };

            var feed_metadict = new Dictionary <string, string>()
            {
                { "feedurl", test_feedurl }
            };

            var evt = new DDay.iCal.Event();

            evt.Categories.Add("a");              // set event categories
            evt.Categories.Add("b");
            evt.Categories.Add("b");              // this dupe should go away

            var list = collector_keene.MaybeApplyCatmap(evt.Categories.ToList(), feed_metadict, "testKeene", "Keene Test Hub");

            list.Sort(String.CompareOrdinal);
            Assert.IsTrue(list.SequenceEqual(new List <string>()
            {
                "a", "b", "l", "m", "n", "o", "p"
            }));
        }
Beispiel #8
0
        /// <summary>
        /// returns true if there is a blank schedule or a schedule that is incomplete
        /// </summary>
        /// <returns></returns>
        public virtual bool HasScheduleWarning()
        {
            DDay.iCal.Event calEvent = GetCalenderEvent();
            if (calEvent != null && calEvent.DTStart != null)
            {
                if (calEvent.RecurrenceRules.Any())
                {
                    IRecurrencePattern rrule = calEvent.RecurrenceRules[0];
                    if (rrule.Frequency == FrequencyType.Weekly)
                    {
                        // if it has a Weekly schedule, but no days are selected, return true that is has a warning
                        if (!rrule.ByDay.Any())
                        {
                            return(true);
                        }
                    }
                    else if (rrule.Frequency == FrequencyType.Monthly)
                    {
                        // if it has a Monthly schedule, but not configured, return true that is has a warning
                        if (!rrule.ByDay.Any() && !rrule.ByMonthDay.Any())
                        {
                            return(true);
                        }
                    }
                }

                // is scheduled, and doesn't have any warnings
                return(false);
            }
            else
            {
                // if there is no CalEvent, it might be scheduled using WeeklyDayOfWeek, but if it isn't, return true that is has a warning
                return(!WeeklyDayOfWeek.HasValue);
            }
        }
Beispiel #9
0
 public UtilsTest()
 {
     StringReader sr = new StringReader(ics_for_filter_tests);
     var ical = (DDay.iCal.iCalendar)iCalendar.LoadFromStream(sr).FirstOrDefault().iCalendar;
     Assert.That(ical.Events.Count == 3);
     test_filter_event = (DDay.iCal.Event)ical.Events[0];
     test_filter_event_2 = (DDay.iCal.Event)ical.Events[1];
     test_filter_event_3 = (DDay.iCal.Event)ical.Events[2];
 }
		public void ProcessRequest(HttpContext context)
		{
			var host = context.Request.Url.Host;

			// initialize calendar item
			var cal = new iCalendar();
			cal.Version = "1.0";

			// find the event
			Telerik.Sitefinity.Events.Model.Event ev;
			using (var fluent = App.WorkWith())
			{
				// TODO: replace this with correct logic for retrieving event
				ev = fluent.Events().Publihed().Get().FirstOrDefault();
			}

			if (ev == null) return;

			var appt = new DDay.iCal.Event();
			appt.Start = new iCalDateTime(ev.EventStart.ToUniversalTime());
			if (ev.EventEnd.HasValue)
				appt.End = new iCalDateTime(ev.EventEnd.Value.ToUniversalTime());
			else
				appt.IsAllDay = true;

			// save and format description
			var description = ev.Content.ToString().Replace("\r\n", "<br /><br/>");
			description = description.Replace("src=\"/", "src=\"http://" + host + "/");
			appt.AddProperty("X-ALT-DESC", description);

			// non-html property
			var reg = new Regex("<(.|\n)+?>");
			appt.Description = reg.Replace(description, "");

			// event location
			var location = ev.Street;
			// location = location == null ? ev.ContentItem.GetMetaData("Street") : string.Concat(location, " (", ev.ContentItem.GetMetaData("Street"), ")");
			appt.Location = location.ToString();

			appt.Summary = ev.Title;

			// url
			//var evUrl = ConfigurationManager.AppSettings[EventsManager.DefaultContentProvider + "Url"];
			//if (string.IsNullOrEmpty(evUrl)) break;
			appt.Url = new Uri("http://www.bing.com");// string.Concat("http://", host, evUrl, ev.ContentItem.UrlWithExtension);
			cal.Events.Add(appt);

			// write calendar feed!
			var ser = new iCalendarSerializer(cal);
			context.Response.Clear();
			context.Response.ContentType = "text/calendar";
			context.Response.AddHeader("content-disposition", "attachment; filename=Calendar.ics");
			context.Response.Write(ser.SerializeToString());
			//context.Response.Flush();
		}
        /// <summary>
        /// Gets the occurrences with option to override the ICal.Event.DTStart
        /// </summary>
        /// <param name="beginDateTime">The begin date time.</param>
        /// <param name="endDateTime">The end date time.</param>
        /// <param name="scheduleStartDateTimeOverride">The schedule start date time override.</param>
        /// <returns></returns>
        public IList <Occurrence> GetOccurrences(DateTime beginDateTime, DateTime?endDateTime, DateTime?scheduleStartDateTimeOverride)
        {
            var occurrences = new List <Occurrence>();

            DDay.iCal.Event calEvent = GetCalendarEvent();
            if (calEvent == null)
            {
                return(occurrences);
            }

            if (scheduleStartDateTimeOverride.HasValue)
            {
                calEvent.DTStart = new DDay.iCal.iCalDateTime(scheduleStartDateTimeOverride.Value);
            }

            if (calEvent.DTStart != null)
            {
                var exclusionDates = new List <DateRange>();
                if (this.CategoryId.HasValue && this.CategoryId.Value > 0)
                {
                    var category = CategoryCache.Get(this.CategoryId.Value);
                    if (category != null)
                    {
                        exclusionDates = category.ScheduleExclusions
                                         .Where(e => e.Start.HasValue && e.End.HasValue)
                                         .ToList();
                    }
                }

                foreach (var occurrence in endDateTime.HasValue ?
                         ScheduleICalHelper.GetOccurrences(calEvent, beginDateTime, endDateTime.Value) :
                         ScheduleICalHelper.GetOccurrences(calEvent, beginDateTime))
                {
                    bool exclude = false;
                    if (exclusionDates.Any() && occurrence.Period.StartTime != null)
                    {
                        var occurrenceStart = occurrence.Period.StartTime.Value;
                        if (exclusionDates.Any(d =>
                                               d.Start.Value <= occurrenceStart &&
                                               d.End.Value >= occurrenceStart))
                        {
                            exclude = true;
                        }
                    }

                    if (!exclude)
                    {
                        occurrences.Add(occurrence);
                    }
                }
            }

            return(occurrences);
        }
Beispiel #12
0
        public UtilsTest()
        {
            StringReader sr   = new StringReader(ics_for_filter_tests);
            var          ical = (DDay.iCal.iCalendar)iCalendar.LoadFromStream(sr).FirstOrDefault().iCalendar;

            Assert.That(ical.Events.Count == 4);
            test_filter_event_0 = (DDay.iCal.Event)ical.Events[0];
            test_filter_event_1 = (DDay.iCal.Event)ical.Events[1];
            test_filter_event_2 = (DDay.iCal.Event)ical.Events[2];
            test_filter_event_3 = (DDay.iCal.Event)ical.Events[3];
        }
Beispiel #13
0
 /// <summary>
 /// Determines whether this instance has a non-empty schedule.
 /// </summary>
 /// <returns></returns>
 public virtual bool HasSchedule()
 {
     DDay.iCal.Event calEvent = GetCalenderEvent();
     if (calEvent != null && calEvent.DTStart != null)
     {
         return(true);
     }
     else
     {
         // if there is no CalEvent, it might be scheduled using WeeklyDayOfWeek
         return(WeeklyDayOfWeek.HasValue);
     }
 }
Beispiel #14
0
        /// <summary>
        /// Creates a string representation of an event.
        /// </summary>
        /// <param name="evt">The event to display</param>
        /// <returns>A string representation of the event.</returns>
        static string GetDescription(Event evt)
        {
            string summary = evt.Summary + ": " + evt.Start.Local.ToShortDateString();

            if (evt.IsAllDay)
            {
                return summary + " (all day)";
            }
            else
            {
                summary += ", " + evt.Start.Local.ToShortTimeString();
                return summary + " (" + Math.Round((double)evt.End.Subtract(evt.Start).TotalHours) + " hours)";
            }
        }
Beispiel #15
0
        public static Event DinnerToEvent(Dinner dinner, iCalendar iCal)
        {
            string eventLink = "http://nrddnr.com/" + dinner.DinnerID;
            Event  evt       = iCal.Create <Event>();

            evt.Start    = new iCalDateTime(dinner.EventDate);
            evt.Duration = new TimeSpan(3, 0, 0);
            evt.Location = dinner.Address;
            evt.Summary  = String.Format("{0} with {1}", dinner.Description, dinner.HostedBy);
            evt.Contacts.Add(dinner.ContactPhone);
            evt.GeographicLocation = new GeographicLocation(dinner.Latitude, dinner.Longitude);
            evt.Url         = new Uri(eventLink);
            evt.Description = eventLink;
            return(evt);
        }
        public static string WriteCalendar(string username, string password)
        {
            ShowRSSCalendar.Login login = new ShowRSSCalendar.Login();

            var episodes = login.GetEpisodeNodes(username, password, ScheduleTypeEnum.upcoming);
            episodes.AddRange(login.GetEpisodeNodes(username, password, ScheduleTypeEnum.aired));

            iCalendar ical = new iCalendar();

            foreach (var item in episodes)
            {
                ExtractNode.Extract(item).CreateEventFromEpisode(ical);
                Event evt = new Event();
            }

            iCalendarSerializer serializer = new iCalendarSerializer();
            return (serializer.SerializeToString(ical));
        }
Beispiel #17
0
        private void WriteCalendar(string username, string password, int offset)
        {
            ShowRSSCalendar.Login login = new ShowRSSCalendar.Login();

            var episodes = login.GetEpisodeNodes(username, password, ScheduleTypeEnum.upcoming);
            episodes.AddRange(login.GetEpisodeNodes(username, password, ScheduleTypeEnum.aired));

            iCalendar ical = new iCalendar();

            if (episodes != null)
                foreach (var item in episodes)
                {
                    ExtractNode.Extract(item).CreateEventFromEpisode(ical, offset);
                    Event evt = new Event();
                }

            iCalendarSerializer serializer = new iCalendarSerializer();
            Response.Write(serializer.SerializeToString(ical));
        }
Beispiel #18
0
        /// <summary>
        /// Gets the next Check-in start date for this Schedule.  
        /// </summary>
        /// <param name="beginDateTime">A <see cref="System.DateTimeOffset"/> representing the base date.</param>
        /// <returns>A <see cref="System.DateTime"/> containing the next time that Check-in begins for this schedule.</returns>
        public virtual DateTime? GetNextCheckInStartTime( DateTimeOffset beginDateTime )
        {
            if ( !IsCheckInEnabled )
            {
                return null;
            }

            // Get the effective start datetime if there's not a specific effective 
            // start time
            DateTime fromDate = beginDateTime.DateTime;
            if ( EffectiveStartDate.HasValue && EffectiveStartDate.Value.CompareTo( fromDate ) > 0 )
            {
                fromDate = EffectiveStartDate.Value;
            }

            DateTime? nextStartTime = null;

            DDay.iCal.Event calEvent = GetCalenderEvent();

            if ( calEvent != null )
            {
                var occurrences = calEvent.GetOccurrences( fromDate, fromDate.AddMonths( 1 ) );
                if ( occurrences.Count > 0 )
                {
                    var nextOccurance = occurrences[0];
                    nextStartTime = nextOccurance.Period.StartTime.Date.AddMinutes( 0 - CheckInStartOffsetMinutes.Value );
                }
            }

            // If no start time was found, return null
            if ( !nextStartTime.HasValue )
            {
                return null;
            }

            // If the Effective end date is prior to next start time, return null
            if ( EffectiveEndDate.HasValue && EffectiveEndDate.Value.CompareTo( nextStartTime.Value ) < 0 )
            {
                return null;
            }

            return nextStartTime.Value;
        }
Beispiel #19
0
        /// <summary>
        /// Gets a list of scheduled start datetimes between the two specified dates, sorted by datetime.
        /// </summary>
        /// <param name="beginDateTime">The begin date time.</param>
        /// <param name="endDateTime">The end date time.</param>
        /// <returns></returns>
        public virtual List <DateTime> GetScheduledStartTimes(DateTime beginDateTime, DateTime endDateTime)
        {
            var result = new List <DateTime>();

            DDay.iCal.Event calEvent = GetCalenderEvent();
            if (calEvent != null)
            {
                // use ThreadSafe helper method to get occurrences
                var occurrences = ScheduleICalHelper.GetOccurrences(calEvent, beginDateTime, endDateTime);

                foreach (var startDateTime in occurrences.Where(a => a.Period != null && a.Period.StartTime != null).Select(a => a.Period.StartTime.Value))
                {
                    // ensure the the datetime is DateTimeKind.Local since iCal returns DateTimeKind.UTC
                    result.Add(DateTime.SpecifyKind(startDateTime, DateTimeKind.Local));
                }
            }

            return(result);
        }
Beispiel #20
0
        /// <summary>
        /// Gets the Schedule's iCalender Event.
        /// </summary>
        /// <value>
        /// A <see cref="DDay.iCal.Event"/> representing the iCalendar event for this Schedule.
        /// </value>
        public virtual DDay.iCal.Event GetCalenderEvent()
        {
            //// iCal is stored as a list of Calendar's each with a list of Events, etc.  
            //// We just need one Calendar and one Event

            StringReader stringReader = new StringReader( iCalendarContent.Trim() );
            var calendarList = DDay.iCal.iCalendar.LoadFromStream( stringReader );
            DDay.iCal.Event calendarEvent = null;
            if ( calendarList.Count > 0 )
            {
                var calendar = calendarList[0] as DDay.iCal.iCalendar;
                if ( calendar != null )
                {
                    calendarEvent = calendar.Events[0] as DDay.iCal.Event;
                }
            }

            return calendarEvent;
        }
Beispiel #21
0
        /// <summary>
        /// Gets the check in times.
        /// </summary>
        /// <param name="beginDateTime">The begin date time.</param>
        /// <returns></returns>
        public virtual List <CheckInTimes> GetCheckInTimes(DateTime beginDateTime)
        {
            var result = new List <CheckInTimes>();

            if (IsCheckInEnabled)
            {
                var scheduledStartTimes = this.GetScheduledStartTimes(beginDateTime, beginDateTime.Date.AddDays(1));

                DDay.iCal.Event calEvent = GetCalenderEvent();
                if (calEvent != null && calEvent.DTStart != null)
                {
                    var occurrences = ScheduleICalHelper.GetOccurrences(calEvent, beginDateTime, beginDateTime.Date.AddDays(1));
                    foreach (var occurrence in occurrences
                             .Where(a =>
                                    a.Period != null &&
                                    a.Period.StartTime != null &&
                                    a.Period.EndTime != null)
                             .Select(a => new {
                        Start = a.Period.StartTime.Value,
                        End = a.Period.EndTime.Value
                    }))
                    {
                        var checkInTimes = new CheckInTimes();
                        checkInTimes.Start        = DateTime.SpecifyKind(occurrence.Start, DateTimeKind.Local);
                        checkInTimes.End          = DateTime.SpecifyKind(occurrence.End, DateTimeKind.Local);
                        checkInTimes.CheckInStart = checkInTimes.Start.AddMinutes(0 - CheckInStartOffsetMinutes.Value);
                        if (CheckInEndOffsetMinutes.HasValue)
                        {
                            checkInTimes.CheckInEnd = checkInTimes.Start.AddMinutes(CheckInEndOffsetMinutes.Value);
                        }
                        else
                        {
                            checkInTimes.CheckInEnd = checkInTimes.End;
                        }

                        result.Add(checkInTimes);
                    }
                }
            }

            return(result);
        }
Beispiel #22
0
        /// <summary>
        /// Gets the next Check-in start date for this Schedule.
        /// </summary>
        /// <param name="beginDateTime">A <see cref="System.DateTime"/> representing the base date.</param>
        /// <returns>A <see cref="System.DateTime"/> containing the next time that Check-in begins for this schedule.</returns>
        public virtual DateTime?GetNextCheckInStartTime(DateTime beginDateTime)
        {
            DateTime?nextStartTime = null;

            if (IsCheckInEnabled)
            {
                DDay.iCal.Event calEvent = GetCalenderEvent();
                if (calEvent != null)
                {
                    var scheduledStartTimes = this.GetScheduledStartTimes(beginDateTime, beginDateTime.AddMonths(1));
                    if (scheduledStartTimes.Count > 0)
                    {
                        var nextScheduledStartTime = scheduledStartTimes[0];
                        nextStartTime = nextScheduledStartTime.AddMinutes(0 - CheckInStartOffsetMinutes.Value);
                    }
                }
            }

            return(nextStartTime);
        }
Beispiel #23
0
    public void TestCreateResource()
    {
      uut.MakeCalendar(user, calendar);

      var theEvent = new Event();
      theEvent.Description = "bar event";
      theEvent.Start = new iCalDateTime(2000, 1, 1, 20, 0, 0);
      theEvent.End = new iCalDateTime(2000, 1, 1, 21, 0, 0);
      theEvent.Summary = "partying hard!";
      var todo = new Todo()
      {
        Description = "stuff todo",
        Summary = "bar todo"
      };

      uut.CreateResource(user, calendar, theEvent);
      uut.CreateResource(user, calendar, todo);

      IICalendar iCal = iCalendar.LoadFromFile(calendarFile)[0];

      Assert.AreEqual(1, iCal.Events.Count);
      Assert.AreEqual(theEvent.Description, iCal.Events[0].Description);
      Assert.AreEqual(theEvent.Start, iCal.Events[0].Start);
      Assert.AreEqual(theEvent.End, iCal.Events[0].End);
      Assert.AreEqual(theEvent.Summary, iCal.Events[0].Summary);

      Assert.AreEqual(1, iCal.Todos.Count);
      Assert.AreEqual(todo.Description, iCal.Todos[0].Description);

      try
      {
        uut.CreateResource(user, calendar, theEvent);
        Assert.Fail("duplicate creation");
      }
      catch (WebException)
      {
      }
    }
Beispiel #24
0
        protected override void WriteFile(System.Web.HttpResponseBase response)
        {
            iCalendar iCal = new iCalendar();

            foreach (Dinner d in this.Dinners)
            {
                try
                {
                    Event e = CalendarHelpers.DinnerToEvent(d, iCal);
                    iCal.Events.Add(e);
                }
                catch (ArgumentOutOfRangeException)
                {
                    //Swallow folks that have dinners in 9999.
                }
            }

            iCalendarSerializer serializer = new iCalendarSerializer(iCal);
            string result = serializer.SerializeToString();

            response.ContentEncoding = Encoding.UTF8;
            response.Write(result);
        }
Beispiel #25
0
        public static void TestDefaultSerialization()
        {
            Console.WriteLine("Serializing using default DDay serializer");

            DateTime startTime = DateTime.Now;

            using (var iCal = new iCalendar())
            {
                iCal.AddLocalTimeZone();
                iCal.AddProperty("X-WR-CALNAME", "CalendarName");

                using (var writer = new FileStream("test.ical", FileMode.OpenOrCreate))
                {
                    for (int count = 0; count < 100000; count++)
                    {
                        var evnt = new Event { Summary = "Event " + count };
                        iCal.Events.Add(evnt);
                    }
                    var serializer = new iCalendarSerializer();
                    serializer.Serialize(iCal, writer, Encoding.UTF8);
                }
            }
            Console.WriteLine("Done: " + (DateTime.Now - startTime));
        }
Beispiel #26
0
        /// <summary>
        /// Gets the calender event.
        /// </summary>
        /// <param name="iCalendarContent">Content of the i calendar.</param>
        /// <returns></returns>
        public static DDay.iCal.Event GetCalenderEvent(string iCalendarContent)
        {
            string trimmedContent = iCalendarContent.Trim();

            if (string.IsNullOrWhiteSpace(trimmedContent))
            {
                return(null);
            }

            DDay.iCal.Event calendarEvent = null;

            lock (ScheduleICalHelper._initLock)
            {
                if (_iCalSchedules.ContainsKey(trimmedContent))
                {
                    return(_iCalSchedules[trimmedContent]);
                }

                StringReader stringReader = new StringReader(trimmedContent);
                var          calendarList = DDay.iCal.iCalendar.LoadFromStream(stringReader);

                //// iCal is stored as a list of Calendar's each with a list of Events, etc.
                //// We just need one Calendar and one Event
                if (calendarList.Count > 0)
                {
                    var calendar = calendarList[0] as DDay.iCal.iCalendar;
                    if (calendar != null)
                    {
                        calendarEvent = calendar.Events[0] as DDay.iCal.Event;
                        _iCalSchedules.AddOrReplace(trimmedContent, calendarEvent);
                    }
                }
            }

            return(calendarEvent);
        }
Beispiel #27
0
    public void TestGetEvents()
    {
      uut.MakeCalendar(user, calendar);

      var evt1 = new Event()
      {
        Summary = "evt1",
        Start = new iCalDateTime(2000, 1, 1, 20, 0, 0),
        End = new iCalDateTime(2000, 1, 1, 21, 0, 0),
      };
      var evt2 = new Event()
      {
        Summary = "evt2",
        Start = new iCalDateTime(2000, 2, 1, 20, 0, 0),
        End = new iCalDateTime(2000, 2, 1, 21, 0, 0),
      };
      var evt3 = new Event()
      {
        Summary = "evt3",
        Location = "adh",
        Start = new iCalDateTime(2000, 3, 1, 20, 0, 0),
        End = new iCalDateTime(2000, 3, 1, 21, 0, 0),
      };
      var todo = new Todo()
      {
        Summary = "todo"
      };

      uut.CreateResource(user, calendar, evt1);
      uut.CreateResource(user, calendar, evt2);
      uut.CreateResource(user, calendar, evt3);
      uut.CreateResource(user, calendar, todo);

      IICalendar events = uut.GetResources(user, calendar);
      Assert.AreEqual(4, events.UniqueComponents.Count());

      var filter = new CompFilter(ResourceType.VCALENDAR);
      Assert.AreEqual(0, uut.GetResources(user, calendar, filter).UniqueComponents.Count());

      var eventFilter = new CompFilter(ResourceType.VEVENT);
      Assert.AreEqual(3, uut.GetResources(user, calendar, eventFilter).UniqueComponents.Count());

      var todoFilter = new CompFilter(ResourceType.VTODO);
      Assert.AreEqual(1, uut.GetResources(user, calendar, todoFilter).UniqueComponents.Count());
    }
Beispiel #28
0
        public void MaybeApplyCatmapAddsExpectedCats()
        {
            var test_feedurl = "test_feedurl";
            var collector_keene = new Collector(new Calinfo("elmcity"), settings);
            collector_keene.per_feed_catmaps[test_feedurl] = new Dictionary<string, string>()
                {
                    { "a", "l,M,n,O,p" },   // this will map
                    { "z", "q" }            // this won't
                };

            var feed_metadict = new Dictionary<string, string>() { { "feedurl", test_feedurl } };

            var evt = new DDay.iCal.Event();

            evt.Categories.Add("a");  // set event categories
            evt.Categories.Add("b");
            evt.Categories.Add("b");  // this dupe should go away

            var list = collector_keene.MaybeApplyCatmap(evt.Categories.ToList(), feed_metadict, "testKeene", "Keene Test Hub");
            list.Sort(String.CompareOrdinal);
            Assert.IsTrue(list.SequenceEqual(new List<string>() { "a", "b", "l", "m", "n", "o", "p" }));
        }
    private iCalendar CreateEntity (int startInHundretDays)
    {
      var calendar = new iCalendar();
      var evt = new Event();
      calendar.Events.Add (evt);
      evt.Start = new iCalDateTime (DateTime.Now.AddDays (startInHundretDays * 100));
      evt.End = new iCalDateTime (DateTime.Now.AddDays (startInHundretDays * 100).AddHours (1));
      evt.Summary = "Event" + startInHundretDays;

      return calendar;
    }
        /// <summary>
        /// Get scheduled events into calendar
        /// </summary>
        /// <returns>Formatted Json events</returns>
        public JsonResult GetEvents( DateTime start, DateTime end,int id = 0)
        {
            IEnumerable<GroupInstance> groupInstances;
            if (id > 0)
            {
                var filteredGroups  =db.GroupInstances.Include(e => e.Group)
                                                  .Include(e => e.Group.Users)
                                                  .ToList()
                                                  .Where(x => x.Group.Users.Where(y => y.UserId == id
                                                       &&(((x.StartDateTime>=start
                                                           ||x.EndDateTime<=end)
                                                       &&x.RecurrenceRule==null)
                                                      ||x.RecurrenceRule!=null)).Any());
                groupInstances = filteredGroups;
            }
            else
            {
                groupInstances = db.GroupInstances.Include(e => e.Group)
                    .Include(e=>e.Group.Users).Where(x=>((x.StartDateTime>=start ||x.EndDateTime<=end)&&x.RecurrenceRule==null)||x.RecurrenceRule!=null).ToList();
            }
            if (groupInstances.Any())
            {
                var recurrence = groupInstances.Where(x => !String.IsNullOrWhiteSpace(x.RecurrenceRule)).FirstOrDefault();
                var list = new List<dynamic>();
                foreach (var instance in groupInstances)
                {
                    if (!String.IsNullOrWhiteSpace(instance.RecurrenceRule))
                    {
                        iCalendarSerializer serializer = new iCalendarSerializer();
                        iCalendarCollection ical = new iCalendarCollection();
                        using (TextReader tr = new StringReader(instance.RecurrenceRule))
                        {
                            ical = (iCalendarCollection)serializer.Deserialize(tr);
                        }

                            Event ev = new Event();
                            if (ical.Count == 0)
                            {
                                RecurrencePattern rp = new RecurrencePattern(instance.RecurrenceRule);
                                ev.RecurrenceRules.Add(rp);
                            }
                            else
                            {
                                ev = (Event)ical.First().Events.First();
                            }
                            var ex = ev.ExceptionDates;
                        ev.Start = new iCalDateTime(instance.StartDateTime);
                        var occ = ev.GetOccurrences(start.AddDays(-1), end);
                        if (occ != null)
                        {
                            foreach (var occurence in occ)
                            {
                                    var user = instance.Group.Users.FirstOrDefault(y => Roles.IsUserInRole(y.UserName, "Teacher"));
                                    var color = "#FFFFFF";
                                    if (user != null)
                                    {
                                        color = user.HexColor;
                                    }
                                    list.Add(new
                                    {
                                        title = instance.Group.Name,
                                        start = CreateNewDateTime(occurence.Period.StartTime, instance.StartDateTime).ToString("s"),
                                        end = CreateNewDateTime(occurence.Period.EndTime, instance.EndDateTime).ToString("s"),
                                        editable = false,
                                        GroupInstanceId = instance.GroupInstanceId,
                                        ClassroomId = instance.ClassroomId,
                                        GroupId = instance.GroupId,
                                        Color = color,
                                        RecurrenceRule = recurrence.RecurrenceRule
                                    });
                            }
                        }
                    }
                    else
                    {
                        list.Add(new
                         {
                             title = instance.Group.Name,
                             start = instance.StartDateTime.ToString("s"),
                             end = instance.EndDateTime.ToString("s"),
                             editable = false,
                             GroupInstanceId = instance.GroupInstanceId,
                             ClassroomId = instance.ClassroomId,
                             GroupId = instance.GroupId,
                             Color = instance.Group.Users.FirstOrDefault(y => Roles.IsUserInRole(y.UserName, "Teacher")).HexColor
                         });

                    }
                }
                return Json(list, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(null, JsonRequestBehavior.AllowGet);
            }
        }
        public ActionResult DeleteConfirmed(int id, string RemoveInstance, string StartDate, string EndDate)
        {
            GroupInstance groupinstance = db.GroupInstances.Find(id);
            if (!String.IsNullOrEmpty(RemoveInstance))
            {
                if (Convert.ToBoolean(RemoveInstance) == false)
                {
                    db.GroupInstances.Remove(groupinstance);
                }
                else
                {
                    iCalendarSerializer serializer = new iCalendarSerializer();
                    iCalendarCollection icalCollection = new iCalendarCollection();
                    using (TextReader tr = new StringReader(groupinstance.RecurrenceRule))
                    {
                        icalCollection = (iCalendarCollection)serializer.Deserialize(tr);
                    }

                    Event ev = new Event();
                    if (icalCollection.Count == 0)
                    {
                        RecurrencePattern rp = new RecurrencePattern(groupinstance.RecurrenceRule);
                        ev.RecurrenceRules.Add(rp);
                    }
                    else
                    {
                        ev = (Event)icalCollection.First().Events.First();
                    }

                    PeriodList pl = new PeriodList();
                    if (ev.ExceptionDates.Count > 0)
                    {
                        pl.AddRange(ev.ExceptionDates.First());
                    }
                    var sd = Convert.ToDateTime(StartDate);
                    var time = new iCalDateTime(sd);

                    pl.Add(time);
                    ev.ExceptionDates.Add(pl);
                    iCalendar ical = new iCalendar();
                    ical.Events.Add(ev);
                    serializer = new iCalendarSerializer(ical);
                    groupinstance.RecurrenceRule = serializer.SerializeToString(ical);
                    db.Entry(groupinstance).State = EntityState.Modified;
                }
                db.SaveChanges();
            }
            else
            {
                    db.GroupInstances.Remove(groupinstance);
                    db.SaveChanges();
            }
            return Content(Boolean.TrueString);
        }
Beispiel #32
0
 public static void AddEventToDDayIcal(iCalendar ical, DDay.iCal.Event evt)
 {
     var ical_evt = new DDay.iCal.Event();
     ical_evt.Categories = evt.Categories;
     ical_evt.Summary = evt.Summary;
     ical_evt.Url = evt.Url;
     ical_evt.Location = evt.Location;
     ical_evt.Description = evt.Description;
     ical_evt.Start = evt.Start;
     if (evt.DTEnd != null && evt.DTEnd.Year != 1)
         ical_evt.End = evt.DTEnd;
     ical_evt.IsAllDay = evt.IsAllDay;
     ical_evt.UID = Event.MakeEventUid(ical_evt);
     ical_evt.GeographicLocation = evt.GeographicLocation;
     ical.Events.Add(ical_evt);
 }
Beispiel #33
0
 public static DDay.iCal.Event MakeTmpEvt(Calinfo calinfo, DateTimeWithZone dtstart, DateTimeWithZone dtend, string title, string url, string location, string description, string lat, string lon, bool allday)
 {
     DDay.iCal.Event evt = new DDay.iCal.Event();  // for export to the intermediate ics file
     evt.Summary = title;
     evt.Url = new Uri(url);
     if (location != null)
         evt.Location = location;
     if (description != null)
         evt.Description = description;
     else
         evt.Description = url;
     if ( calinfo == null )
         MakeGeo(calinfo, evt, lat, lon);
     else
         MakeGeo(evt, lat, lon);
     evt.Start = new iCalDateTime(dtstart.LocalTime);               // always local because the final ics file will use vtimezone
     evt.Start.TZID = calinfo.tzinfo.Id;
     if (!dtend.Equals(DateTimeWithZone.MinValue(calinfo.tzinfo)))
     {
         evt.End = new iCalDateTime(dtend.LocalTime);
         evt.End.TZID = calinfo.tzinfo.Id;
     }
     evt.IsAllDay = allday;
     evt.UID = Event.MakeEventUid(evt);
     return evt;
 }
        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
        public void ProcessRequest(HttpContext context)
        {
            var host = context.Request.Url.Host;

            // TODO: Support Filtering by date/month

            // TODO: Support filtering by category

            // initializie calendar
            var cal = new iCalendar();

            cal.Version = "1.0";

            // get events +/- 6 months
            IQueryable events;

            using (var fluent = App.WorkWith())
            {
                var center = new DateTime(year, month, 1);
                var start  = center.AddMonths(-6);
                var end    = center.AddMonths(6);

                events = fluent.Events().Where(e => e.EventStart >= start && e.EventEnd <= end && e.Status == Telerik.Sitefinity.GenericContent.Model.ContentLifecycleStatus.Live).Get();
            }

            foreach (Telerik.Sitefinity.Events.Model.Event ev in events)
            {
                var appt = new DDay.iCal.Event();
                appt.Start = new iCalDateTime(ev.EventStart.ToUniversalTime());
                if (ev.EventEnd.HasValue)
                {
                    appt.End = new iCalDateTime(ev.EventEnd.Value.ToUniversalTime());
                }
                else
                {
                    appt.IsAllDay = true;
                }

                // save and format description
                var description = ev.Content.ToString().Replace("\r\n", "<br /><br/>");
                description = description.Replace("src=\"/", "src=\"http://" + host + "/");
                appt.AddProperty("X-ALT-DESC", description);

                // non-html property
                var reg = new Regex("<(.|\n)+?>");
                appt.Description = reg.Replace(description, "");

                // event location
                var location = ev.Street;
                // location = location == null ? ev.ContentItem.GetMetaData("Street") : string.Concat(location, " (", ev.ContentItem.GetMetaData("Street"), ")");
                appt.Location = location.ToString();

                appt.Summary = ev.Title;

                // url
                //var evUrl = ConfigurationManager.AppSettings[EventsManager.DefaultContentProvider + "Url"];
                //if (string.IsNullOrEmpty(evUrl)) break;
                appt.Url = new Uri("http://www.bing.com");                // string.Concat("http://", host, evUrl, ev.ContentItem.UrlWithExtension);
                cal.Events.Add(appt);
            }

            // write calendar feed!
            var ser = new iCalendarSerializer(cal);

            context.Response.Clear();
            context.Response.ContentType = "text/calendar";
            context.Response.AddHeader("content-disposition", "attachment; filename=Calendar.ics");
            context.Response.Write(ser.SerializeToString());
            //context.Response.Flush();
        }
        public void ProcessRequest(HttpContext context)
        {
            var host = context.Request.Url.Host;

            // initialize calendar item
            var cal = new iCalendar();

            cal.Version = "1.0";

            // find the event
            Telerik.Sitefinity.Events.Model.Event ev;
            using (var fluent = App.WorkWith())
            {
                // TODO: replace this with correct logic for retrieving event
                ev = fluent.Events().Publihed().Get().FirstOrDefault();
            }

            if (ev == null)
            {
                return;
            }

            var appt = new DDay.iCal.Event();

            appt.Start = new iCalDateTime(ev.EventStart.ToUniversalTime());
            if (ev.EventEnd.HasValue)
            {
                appt.End = new iCalDateTime(ev.EventEnd.Value.ToUniversalTime());
            }
            else
            {
                appt.IsAllDay = true;
            }

            // save and format description
            var description = ev.Content.ToString().Replace("\r\n", "<br /><br/>");

            description = description.Replace("src=\"/", "src=\"http://" + host + "/");
            appt.AddProperty("X-ALT-DESC", description);

            // non-html property
            var reg = new Regex("<(.|\n)+?>");

            appt.Description = reg.Replace(description, "");

            // event location
            var location = ev.Street;

            appt.Location = location.ToString();

            appt.Summary = ev.Title;

            // url
            appt.Url = new Uri("http://www.bing.com");
            cal.Events.Add(appt);

            // write calendar feed!
            var ser = new iCalendarSerializer(cal);

            context.Response.Clear();
            context.Response.ContentType = "text/calendar";
            context.Response.AddHeader("content-disposition", "attachment; filename=Calendar.ics");
            context.Response.Write(ser.SerializeToString());
        }
Beispiel #36
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>
        public override 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");
            }
        }
Beispiel #37
0
        public ActionResult Create(FormCollection collection)
        {
            if (collection == null ||
                string.IsNullOrEmpty(collection["EndDate"]) ||
                string.IsNullOrEmpty(collection["Location"]) ||
                string.IsNullOrEmpty(collection["StartDate"]) ||
                string.IsNullOrEmpty(collection["Title"]))
                return new HttpErrorCodeResult(400, "One of the required form values was not provided in the posted collection");

            DateTime startDate = new DateTime(DateTime.Parse(collection["StartDate"]).Ticks, DateTimeKind.Local).ToUniversalTime();
            DateTime endDate = new DateTime(DateTime.Parse(collection["EndDate"]).Ticks, DateTimeKind.Local).ToUniversalTime();

            if (startDate < DateTime.UtcNow)
                return new HttpErrorCodeResult(400, "Events cannot be created in the past");
            
            if (endDate <= startDate)
                endDate = startDate.AddHours(1);

            Event e = new Event
                      {
                          CreateDate = DateTime.UtcNow,
                          EndDate = endDate,
                          HostUserID = CurrentUserId,
                          Location = collection["Location"],
                          LongDescription = collection["LongDescription"],
                          ShortDescription = collection["ShortDescription"],
                          StartDate = startDate,
                          Title = collection["Title"]
                      };
            Context.Events.AddObject(e);
            Context.SaveChanges();

            if (e.LongDescription != null)
            {
                Article article = new Article
                {
                    Body = e.LongDescription,
                    PosterUserID = CurrentUserId.Value,
                    PublicationDate = DateTime.UtcNow,
                    Title = e.Title,
                    CreateDate = DateTime.UtcNow
                };
                Context.Articles.AddObject(article);
                Context.SaveChanges();

                e.Article = article;
                e.ArticleID = article.ID;
                Context.SaveChanges();
            }

            return Json(new
                        {
                            eventId = e.ID,
                            startDate = string.Format("{0:MMM dd, yyyy HH:mm}", e.StartDate.ToLocalTime()),
                            endDate = string.Format("{0:MMM dd, yyyy HH:mm}", e.EndDate.ToLocalTime())
                        });
        }
Beispiel #38
0
        public iCalResult ICal(int id)
        {
            var ev = Context.Events
                .Where(a => a.ID == id)
                .SingleOrDefault();

            if (ev == null)
                return null;

            var calendar = new iCalendar();
            calendar.Version = "1.0"; // Compat with Outlook 2003

            var calEvent = new DDay.iCal.Event
                               {
                                   Description = string.Format("{0} {1}", ev.ShortDescription, ev.LongDescription),
                                   End = new iCalDateTime(ev.EndDate),
                                   Location = ev.Location,
                                   Start = new iCalDateTime(ev.StartDate),
                                   Summary = ev.Title
                               };
            calendar.Events.Add(calEvent);

            iCalendarSerializer serializer = new iCalendarSerializer();
            string serialized = serializer.SerializeToString(calendar);

            return new iCalResult(serialized);
        }
Beispiel #39
0
        /// <summary>
        /// Converts a Calendar to an IICalendar.
        /// </summary>
        /// <param name="calendar">The calendar object to convert.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if a calendar is not provided.</exception>
        /// <returns>The converted IICalendar, or null if the calendar couldn't be converted.</returns>
        private static IICalendar ToIICalendar(Calendar calendar)
        {
            // Check if a calendar was provided.
            if (calendar != null)
            {
                // A calendar was provided.

                // Create the iCalendar calendar to populate with events.
                IICalendar iCalCalendar = new DDay.iCal.iCalendar();

                // Populate the calendar with events.
                foreach (Event calendarEvent in calendar.Events)
                {
                    DDay.iCal.Event iCalEvent = new DDay.iCal.Event
                    {
                        Summary     = calendarEvent.Title,
                        Description = calendarEvent.Description,
                        Location    = calendarEvent.Location
                    };
                    if (calendarEvent.Canceled.HasValue && calendarEvent.Canceled == true)
                    {
                        iCalEvent.Status = EventStatus.Cancelled;
                    }
                    // Set the priority to the lowest value in its defined range.
                    switch (calendarEvent.Priority)
                    {
                    case Event.PriorityLevels.High:
                        iCalEvent.Priority = PRIORITY_THRESHOLD_UNDEFINED + 1;
                        break;

                    case Event.PriorityLevels.Medium:
                        iCalEvent.Priority = PRIORITY_THRESHOLD_HIGH + 1;
                        break;

                    case Event.PriorityLevels.Low:
                        iCalEvent.Priority = PRIORITY_THRESHOLD_MEDIUM + 1;
                        break;
                    }
                    if (calendarEvent.StartDate.HasValue)
                    {
                        iCalEvent.Start = new iCalDateTime(calendarEvent.StartDate.Value);
                    }
                    if (calendarEvent.EndDate.HasValue)
                    {
                        iCalEvent.End = new iCalDateTime(calendarEvent.EndDate.Value);
                    }
                    if (calendarEvent.AllDayEvent.HasValue)
                    {
                        iCalEvent.IsAllDay = calendarEvent.AllDayEvent.Value;
                    }
                    else
                    {
                        iCalEvent.IsAllDay = false;
                    }
                    if (!string.IsNullOrWhiteSpace(calendarEvent.ContactName))
                    {
                        iCalEvent.Contacts = new List <string> {
                            calendarEvent.ContactName
                        };
                    }
                    if (calendarEvent.LastUpdated.HasValue)
                    {
                        iCalEvent.LastModified = new iCalDateTime(calendarEvent.LastUpdated.Value);
                    }

                    // Add the event to the iCalendar calendar.
                    iCalCalendar.Events.Add(iCalEvent);
                }

                // Return the populated iCalendar calendar.
                return(iCalCalendar);
            }
            else
            {
                // A calendar was not provided.
                throw new ArgumentNullException("calendar");
            }
        }
Beispiel #40
0
        /// <summary>
        /// Converts a Calendar to an IICalendar.
        /// </summary>
        /// <param name="calendar">The calendar object to convert.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if a calendar is not provided.</exception>
        /// <returns>The converted IICalendar, or null if the calendar couldn't be converted.</returns>
        private static IICalendar ToIICalendar(Calendar calendar)
        {
            // Check if a calendar was provided.
            if (calendar != null)
            {
                // A calendar was provided.

                // Create the iCalendar calendar to populate with events.
                IICalendar iCalCalendar = new DDay.iCal.iCalendar();

                // Populate the calendar with events.
                foreach (Event calendarEvent in calendar.Events)
                {
                    DDay.iCal.Event iCalEvent = new DDay.iCal.Event
                    {
                        Summary = calendarEvent.Title,
                        Description = calendarEvent.Description,
                        Location = calendarEvent.Location
                    };
                    if (calendarEvent.Canceled.HasValue && calendarEvent.Canceled == true)
                    {
                        iCalEvent.Status = EventStatus.Cancelled;
                    }
                    // Set the priority to the lowest value in its defined range.
                    switch (calendarEvent.Priority)
                    {
                        case Event.PriorityLevels.High:
                            iCalEvent.Priority = PRIORITY_THRESHOLD_UNDEFINED + 1;
                            break;
                        case Event.PriorityLevels.Medium:
                            iCalEvent.Priority = PRIORITY_THRESHOLD_HIGH + 1;
                            break;
                        case Event.PriorityLevels.Low:
                            iCalEvent.Priority = PRIORITY_THRESHOLD_MEDIUM + 1;
                            break;
                    }
                    if (calendarEvent.StartDate.HasValue)
                    {
                        iCalEvent.Start = new iCalDateTime(calendarEvent.StartDate.Value);
                    }
                    if (calendarEvent.EndDate.HasValue)
                    {
                        iCalEvent.End = new iCalDateTime(calendarEvent.EndDate.Value);
                    }
                    if (calendarEvent.AllDayEvent.HasValue)
                    {
                        iCalEvent.IsAllDay = calendarEvent.AllDayEvent.Value;
                    }
                    else
                    {
                        iCalEvent.IsAllDay = false;
                    }
                    if (!string.IsNullOrWhiteSpace(calendarEvent.ContactName))
                    {
                        iCalEvent.Contacts = new List<string> { calendarEvent.ContactName };
                    }
                    if (calendarEvent.LastUpdated.HasValue)
                    {
                        iCalEvent.LastModified = new iCalDateTime(calendarEvent.LastUpdated.Value);
                    }

                    // Add the event to the iCalendar calendar.
                    iCalCalendar.Events.Add(iCalEvent);
                }

                // Return the populated iCalendar calendar.
                return iCalCalendar;
            }
            else
            {
                // A calendar was not provided.
                throw new ArgumentNullException("calendar");
            }
        }
Beispiel #41
0
        /// <summary>
        /// Gets the Friendly Text of the Calendar Event.
        /// For example, "Every 3 days at 10:30am", "Monday, Wednesday, Friday at 5:00pm", "Saturday at 4:30pm"
        /// </summary>
        /// <returns>A <see cref="System.String"/> containing a friendly description of the Schedule.</returns>
        public string ToFriendlyScheduleText()
        {
            // init the result to just the schedule name just in case we can't figure out the FriendlyText
            string result = this.Name;

            DDay.iCal.Event calendarEvent = this.GetCalenderEvent();
            if (calendarEvent != null && calendarEvent.DTStart != null)
            {
                string startTimeText = calendarEvent.DTStart.Value.TimeOfDay.ToTimeString();
                if (calendarEvent.RecurrenceRules.Any())
                {
                    // some type of recurring schedule

                    IRecurrencePattern rrule = calendarEvent.RecurrenceRules[0];
                    switch (rrule.Frequency)
                    {
                    case FrequencyType.Daily:
                        result = "Daily";

                        if (rrule.Interval > 1)
                        {
                            result += string.Format(" every {0} days", rrule.Interval);
                        }

                        result += " at " + startTimeText;

                        break;

                    case FrequencyType.Weekly:

                        result = rrule.ByDay.Select(a => a.DayOfWeek.ConvertToString()).ToList().AsDelimited(",");
                        if (string.IsNullOrEmpty(result))
                        {
                            // no day selected, so it has an incomplete schedule
                            return("No Scheduled Days");
                        }

                        if (rrule.Interval > 1)
                        {
                            result += string.Format(" every {0} weeks", rrule.Interval);
                        }

                        result += " at " + startTimeText;

                        break;

                    case FrequencyType.Monthly:

                        if (rrule.ByMonthDay.Count > 0)
                        {
                            // Day X of every X Months (we only support one day in the ByMonthDay list)
                            int monthDay = rrule.ByMonthDay[0];
                            result = string.Format("Day {0} of every ", monthDay);
                            if (rrule.Interval > 1)
                            {
                                result += string.Format("{0} months", rrule.Interval);
                            }
                            else
                            {
                                result += "month";
                            }

                            result += " at " + startTimeText;
                        }
                        else if (rrule.ByDay.Count > 0)
                        {
                            // The Nth <DayOfWeekName> (we only support one day in the ByDay list)
                            IWeekDay bydate = rrule.ByDay[0];
                            if (NthNames.ContainsKey(bydate.Offset))
                            {
                                result = string.Format("The {0} {1} of every month", NthNames[bydate.Offset], bydate.DayOfWeek.ConvertToString());
                            }
                            else
                            {
                                // unsupported case (just show the name)
                            }

                            result += " at " + startTimeText;
                        }
                        else
                        {
                            // unsupported case (just show the name)
                        }

                        break;

                    default:
                        // some other type of recurring type (probably specific dates).  Just return the Name of the schedule

                        break;
                    }
                }
                else
                {
                    // not any type of recurring, runs once
                    result = "Once at " + calendarEvent.DTStart.Value.ToString();
                }
            }
            else
            {
                if (WeeklyDayOfWeek.HasValue)
                {
                    result = WeeklyDayOfWeek.Value.ConvertToString();
                    if (WeeklyTimeOfDay.HasValue)
                    {
                        result += " at " + WeeklyTimeOfDay.Value.ToTimeString();
                    }
                }
                else
                {
                    // no start time.  Nothing scheduled
                    return("No Schedule");
                }
            }

            return(result);
        }
Beispiel #42
0
        /// <summary>
        /// Gets the Friendly Text of the Calendar Event.
        /// For example, "Every 3 days at 10:30am", "Monday, Wednesday, Friday at 5:00pm", "Saturday at 4:30pm"
        /// </summary>
        /// <param name="condensed">if set to <c>true</c> [condensed].</param>
        /// <returns>
        /// A <see cref="System.String" /> containing a friendly description of the Schedule.
        /// </returns>
        public string ToFriendlyScheduleText(bool condensed)
        {
            // init the result to just the schedule name just in case we can't figure out the FriendlyText
            string result = this.Name;

            DDay.iCal.Event calendarEvent = this.GetCalenderEvent();
            if (calendarEvent != null && calendarEvent.DTStart != null)
            {
                string startTimeText = calendarEvent.DTStart.Value.TimeOfDay.ToTimeString();
                if (calendarEvent.RecurrenceRules.Any())
                {
                    // some type of recurring schedule

                    IRecurrencePattern rrule = calendarEvent.RecurrenceRules[0];
                    switch (rrule.Frequency)
                    {
                    case FrequencyType.Daily:
                        result = "Daily";

                        if (rrule.Interval > 1)
                        {
                            result += string.Format(" every {0} days", rrule.Interval);
                        }

                        result += " at " + startTimeText;

                        break;

                    case FrequencyType.Weekly:

                        result = rrule.ByDay.Select(a => a.DayOfWeek.ConvertToString()).ToList().AsDelimited(",");
                        if (string.IsNullOrEmpty(result))
                        {
                            // no day selected, so it has an incomplete schedule
                            return("No Scheduled Days");
                        }

                        if (rrule.Interval > 1)
                        {
                            result += string.Format(" every {0} weeks", rrule.Interval);
                        }

                        result += " at " + startTimeText;

                        break;

                    case FrequencyType.Monthly:

                        if (rrule.ByMonthDay.Count > 0)
                        {
                            // Day X of every X Months (we only support one day in the ByMonthDay list)
                            int monthDay = rrule.ByMonthDay[0];
                            result = string.Format("Day {0} of every ", monthDay);
                            if (rrule.Interval > 1)
                            {
                                result += string.Format("{0} months", rrule.Interval);
                            }
                            else
                            {
                                result += "month";
                            }

                            result += " at " + startTimeText;
                        }
                        else if (rrule.ByDay.Count > 0)
                        {
                            // The Nth <DayOfWeekName> (we only support one day in the ByDay list)
                            IWeekDay bydate = rrule.ByDay[0];
                            if (NthNames.ContainsKey(bydate.Offset))
                            {
                                result = string.Format("The {0} {1} of every month", NthNames[bydate.Offset], bydate.DayOfWeek.ConvertToString());
                            }
                            else
                            {
                                // unsupported case (just show the name)
                            }

                            result += " at " + startTimeText;
                        }
                        else
                        {
                            // unsupported case (just show the name)
                        }

                        break;

                    default:
                        // some other type of recurring type (probably specific dates).  Just return the Name of the schedule

                        break;
                    }
                }
                else
                {
                    // not any type of recurring, might be one-time or from specific dates, etc
                    var dates = calendarEvent.GetOccurrences(DateTime.MinValue, DateTime.MaxValue).Where(a =>
                                                                                                         a.Period != null &&
                                                                                                         a.Period.StartTime != null)
                                .Select(a => a.Period.StartTime.Value)
                                .OrderBy(a => a).ToList();

                    if (dates.Count() > 1)
                    {
                        if (condensed || dates.Count() > 99)
                        {
                            result = string.Format("Multiple dates between {0} and {1}", dates.First().ToShortDateString(), dates.Last().ToShortDateString());
                        }
                        else
                        {
                            var listHtml = "<ul class='list-unstyled'>" + Environment.NewLine;
                            foreach (var date in dates)
                            {
                                listHtml += string.Format("<li>{0}</li>", date.ToShortDateTimeString()) + Environment.NewLine;
                            }

                            listHtml += "</ul>";

                            result = listHtml;
                        }
                    }
                    else if (dates.Count() == 1)
                    {
                        result = "Once at " + calendarEvent.DTStart.Value.ToShortDateTimeString();
                    }
                    else
                    {
                        return("No Schedule");
                    }
                }
            }
            else
            {
                if (WeeklyDayOfWeek.HasValue)
                {
                    result = WeeklyDayOfWeek.Value.ConvertToString();
                    if (WeeklyTimeOfDay.HasValue)
                    {
                        result += " at " + WeeklyTimeOfDay.Value.ToTimeString();
                    }
                }
                else
                {
                    // no start time.  Nothing scheduled
                    return("No Schedule");
                }
            }

            return(result);
        }
Beispiel #43
0
        /// <summary>
        /// Creates the iCalendar object and populates it with events
        /// </summary>
        /// <param name="calendarProps">The calendar props.</param>
        /// <returns></returns>
        private iCalendar CreateICalendar(CalendarProps calendarProps, string interactionDeviceType)
        {
            // Get a list of confirmed attendances filtered by calendarProps
            List <Attendance> attendances = GetAttendances(calendarProps);

            // Create the iCalendar
            iCalendar icalendar = new iCalendar();

            icalendar.AddLocalTimeZone();
            TimeSpan duration          = TimeSpan.MinValue;
            int      currentScheduleId = -1;

            // Create each of the attendances
            foreach (var attendance in attendances)
            {
                using (var rockContext = new RockContext())
                {
                    var attendanceOccurrenceService = new AttendanceOccurrenceService(rockContext);

                    var schedule = attendanceOccurrenceService
                                   .Queryable()
                                   .AsNoTracking()
                                   .Where(a => a.Id == attendance.OccurrenceId)
                                   .Select(a => a.Schedule)
                                   .FirstOrDefault();

                    string scheduleName = schedule.Name;

                    // TODO: Construct a description that includes the group leader contact info and the URL to the schedule toolbox.
                    string description = schedule.Description;

                    string locationName = attendanceOccurrenceService
                                          .Queryable()
                                          .AsNoTracking()
                                          .Where(a => a.Id == attendance.OccurrenceId)
                                          .Select(a => a.Location.Name)
                                          .FirstOrDefault() ?? string.Empty;

                    if (schedule.Id != currentScheduleId)
                    {
                        // We have to get the duration from Schedule.iCal for this attendance.
                        // Attendances are ordered by scheduleId so this only happens once for each unique schedule.
                        iCalendarSerializer serializer = new iCalendarSerializer();
                        iCalendarCollection ical       = ( iCalendarCollection )serializer.Deserialize(schedule.iCalendarContent.ToStreamReader());
                        duration          = ical[0].Events[0].Duration;
                        currentScheduleId = schedule.Id;
                    }

                    var iCalEvent = new DDay.iCal.Event();
                    iCalEvent.Summary  = scheduleName;
                    iCalEvent.Location = locationName;
                    iCalEvent.DTStart  = new DDay.iCal.iCalDateTime(attendance.StartDateTime);
                    iCalEvent.DTStart.SetTimeZone(icalendar.TimeZones[0]);
                    iCalEvent.Duration = duration;

                    // Don't set the description prop for outlook to force it to use the X-ALT-DESC property which can have markup.
                    if (interactionDeviceType != "Outlook")
                    {
                        iCalEvent.Description = description.ConvertBrToCrLf().SanitizeHtml();
                    }

                    // HTML version of the description for outlook
                    iCalEvent.AddProperty("X-ALT-DESC;FMTTYPE=text/html", "<html>" + description + "</html>");

                    // classification: "PUBLIC", "PRIVATE", "CONFIDENTIAL"
                    iCalEvent.Class = "PUBLIC";

                    //Add contact info for the group leader
                    int groupId = attendanceOccurrenceService
                                  .Queryable()
                                  .AsNoTracking()
                                  .Where(a => a.Id == attendance.OccurrenceId)
                                  .Select(a => a.GroupId)
                                  .FirstOrDefault() ?? -1;

                    Person groupLeader = new GroupMemberService(rockContext).GetLeaders(groupId).AsNoTracking().Select(m => m.Person).FirstOrDefault() ?? null;

                    if (groupLeader != null)
                    {
                        iCalEvent.Organizer            = new Organizer(string.Format("MAILTO:{0}", groupLeader.Email));
                        iCalEvent.Organizer.CommonName = groupLeader.FullName;

                        // Outlook doesn't seem to use Contacts or Comments
                        string contactName  = !string.IsNullOrEmpty(groupLeader.FullName) ? "Name: " + groupLeader.FullName : string.Empty;
                        string contactEmail = !string.IsNullOrEmpty(groupLeader.Email) ? ", Email: " + groupLeader.Email : string.Empty;
                        string contactInfo  = contactName + contactEmail;

                        iCalEvent.Contacts.Add(contactInfo);
                        iCalEvent.Comments.Add(contactInfo);
                    }

                    icalendar.Events.Add(iCalEvent);
                }
            }

            return(icalendar);
        }
        /// <summary>
        /// Function is called to create the course ics file
        /// Function is called everytime the course calendar needs to be updated
        /// </summary>
        /// <param name="id"></param>
        public void CreateCourseCalendar(int id)
        {
            //Get the Course
            var course = (from d in db.Courses
                          where d.ID == id
                          select new
            {
                d.StartDate,
                d.EndDate,
                d.Prefix,
                d.Number,
                d.Semester,
                d.Year,
                d.CourseMeetings,
                d.CourseBreaks,
                d.ID
            }).FirstOrDefault();


            //get course events
            var events = (from e in db.Events
                          where e.Poster.AbstractCourseID == ActiveCourseUser.AbstractCourseID &&
                          e.StartDate >= course.StartDate &&
                          e.StartDate <= course.EndDate &&
                          e.Approved
                          select new
            {
                e.StartDate,
                e.EndDate,
                e.Title,
                e.Description
            }).ToList();

            //Create the calendar object
            iCalendar courseCalendar = new iCalendar();

            //initalize the Calendar object
            courseCalendar.AddTimeZone(DateTimeExtensions.GetTimeZone(((Course)ActiveCourseUser.AbstractCourse).TimeZoneOffset));
            courseCalendar.Method    = "PUBLISH";
            courseCalendar.Name      = "VCALENDAR";
            courseCalendar.Version   = "2.0";
            courseCalendar.ProductID = "-//Washington State University//PLUS.OSBLE.org//EN";
            courseCalendar.Scale     = "GREGORIAN";
            courseCalendar.AddProperty("X-WR-CALNAME", course.Prefix + "-" + course.Number + "-" + course.Semester + "-" + course.Year);

            //get course breaks
            if (ActiveCourseUser.AbstractCourse is Course && ((ActiveCourseUser.AbstractCourse as Course).ShowMeetings == true))
            {
                foreach (CourseMeeting cm in course.CourseMeetings)
                {
                    StringBuilder rpPattern = new StringBuilder("FREQ=WEEKLY;UNTIL=");
                    rpPattern.Append(new iCalDateTime(course.EndDate.UTCToCourse(ActiveCourseUser.AbstractCourseID)).ToString(@"yyyyMMdd\THHmmss\Z"));
                    rpPattern.Append(";WKST=SU;BYDAY=");
                    if (cm.Sunday)
                    {
                        rpPattern.Append("SU,");
                    }
                    if (cm.Monday)
                    {
                        rpPattern.Append("MO,");
                    }
                    if (cm.Tuesday)
                    {
                        rpPattern.Append("TU,");
                    }
                    if (cm.Wednesday)
                    {
                        rpPattern.Append("WE,");
                    }
                    if (cm.Thursday)
                    {
                        rpPattern.Append("TH,");
                    }
                    if (cm.Friday)
                    {
                        rpPattern.Append("FR,");
                    }
                    if (cm.Saturday)
                    {
                        rpPattern.Append("SA");
                    }

                    //trim trailing comma if it is there
                    if (rpPattern[rpPattern.Length - 1] == ',')
                    {
                        rpPattern.Remove(rpPattern.Length - 1, 1);
                    }

                    RecurringComponent recurringComponent = new RecurringComponent();
                    RecurrencePattern  pattern            = new RecurrencePattern(rpPattern.ToString());

                    DDay.iCal.Event evt = courseCalendar.Create <DDay.iCal.Event>();
                    //may cause issues
                    DateTime evtStart = DateTime.SpecifyKind(course.StartDate, DateTimeKind.Utc);
                    evtStart = evtStart.Add(cm.StartTime.TimeOfDay);
                    DateTime evtEnd = DateTime.SpecifyKind(course.StartDate, DateTimeKind.Utc);
                    evtEnd = evtEnd.Add(cm.EndTime.TimeOfDay);

                    //we need to test if right NOW is in DST.
                    //case: course starts during DST, and it's now after DST, result: after DST event is now wrong.
                    DateTime currentTime = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day,
                                                        evtStart.Hour, evtStart.Minute, evtStart.Second, DateTimeKind.Utc);
                    bool isDaylight = TimeZoneInfo.Local.IsDaylightSavingTime(currentTime.UTCToCourse(ActiveCourseUser.AbstractCourseID));

                    if (isDaylight)
                    {
                        evt.Start        = new iCalDateTime(evtStart.UTCToCourse(ActiveCourseUser.AbstractCourseID));
                        evt.End          = new iCalDateTime(evtEnd.UTCToCourse(ActiveCourseUser.AbstractCourseID));
                        evt.LastModified = new iCalDateTime(DateTime.Now);
                        evt.Summary      = cm.Name;
                        evt.Location     = cm.Location;
                        evt.RecurrenceRules.Add(pattern);
                    }
                    else //no longer DST
                    {
                        bool matchingStartDay = false;

                        /*
                         * if there happens to be a "meeting times" in the database without a day of the week associated with
                         * the meeting, we need to skip the while and switch case, otherwise it's an infinite loop!
                         */
                        bool meetingTimeWithoutDaysOfWeek = cm.Sunday || cm.Monday || cm.Tuesday || cm.Wednesday ||
                                                            cm.Thursday || cm.Friday || cm.Saturday ? false : true;

                        int count = 0; //infinite loop protection x2!

                        //WHILE matchingStartDay is false (default false) AND the meeting time has at least one day of the week
                        //AND if we've hit a count of 7, that means we've already checked each day of the week and will never find one!
                        //exit while if we fail either of these conditions!
                        while ((!matchingStartDay && !meetingTimeWithoutDaysOfWeek) && count < 7)
                        {
                            switch (currentTime.DayOfWeek) //find which day of the week for this meeting
                            {
                            case DayOfWeek.Monday:
                                if (cm.Monday)
                                {
                                    matchingStartDay = true;
                                }
                                break;

                            case DayOfWeek.Tuesday:
                                if (cm.Tuesday)
                                {
                                    matchingStartDay = true;
                                }
                                break;

                            case DayOfWeek.Wednesday:
                                if (cm.Wednesday)
                                {
                                    matchingStartDay = true;
                                }
                                break;

                            case DayOfWeek.Thursday:
                                if (cm.Thursday)
                                {
                                    matchingStartDay = true;
                                }
                                break;

                            case DayOfWeek.Friday:
                                if (cm.Friday)
                                {
                                    matchingStartDay = true;
                                }
                                break;

                            case DayOfWeek.Saturday:
                                if (cm.Saturday)
                                {
                                    matchingStartDay = true;
                                }
                                break;

                            case DayOfWeek.Sunday:
                                if (cm.Sunday)
                                {
                                    matchingStartDay = true;
                                }
                                break;

                            default:
                                matchingStartDay = false;
                                break;
                            }

                            if (!matchingStartDay)
                            {
                                currentTime = new DateTime(currentTime.Year, currentTime.Month, currentTime.AddDays(1).Day,
                                                           evtStart.Hour, evtStart.Minute, evtStart.Second, DateTimeKind.Utc);
                            }
                            count++; //infinite loop protection x2! if we've reached 7 we've cycled all weekdays, so get us out of here!
                        }

                        //proceed only if there was a day of the week found for this course meeting time
                        if (!meetingTimeWithoutDaysOfWeek && matchingStartDay)
                        {
                            evt.Start        = new iCalDateTime(currentTime.UTCToCourse(ActiveCourseUser.AbstractCourseID));
                            evt.End          = new iCalDateTime(evtEnd.UTCToCourse(ActiveCourseUser.AbstractCourseID));
                            evt.LastModified = new iCalDateTime(DateTime.Now);
                            evt.Summary      = cm.Name;
                            evt.Location     = cm.Location;
                            evt.RecurrenceRules.Add(pattern);
                        }
                    }
                }

                //create the course breaks
                foreach (CourseBreak cb in course.CourseBreaks)
                {
                    DDay.iCal.Event evt      = courseCalendar.Create <DDay.iCal.Event>();
                    DateTime        evtStart = cb.StartDate.Date;
                    DateTime        evtEnd   = cb.EndDate.Date.AddDays(1);

                    evt.Summary      = cb.Name;
                    evt.Start        = new iCalDateTime(evtStart);
                    evt.End          = new iCalDateTime(evtEnd);
                    evt.LastModified = new iCalDateTime(DateTime.Now);
                }
            }//end if

            //add all the events to the calendar
            foreach (var e in events)
            {
                DDay.iCal.Event evt = courseCalendar.Create <DDay.iCal.Event>();

                evt.Start = new iCalDateTime(e.StartDate.UTCToCourse(ActiveCourseUser.AbstractCourseID));
                if (e.EndDate == null)
                {
                    evt.End = new iCalDateTime(e.StartDate.UTCToCourse(ActiveCourseUser.AbstractCourseID));
                    evt.End.AddMinutes(1);
                }
                else
                {
                    evt.End = new iCalDateTime(((DateTime)e.EndDate).UTCToCourse(ActiveCourseUser.AbstractCourseID));
                }

                evt.Summary = e.Title;
                if (e.Description != null)
                {
                    evt.Description = e.Description;
                }
            }

            // Create a serialization context and serializer factory.
            // These will be used to build the serializer for our object.
            ISerializationContext ctx     = new SerializationContext();
            ISerializerFactory    factory = new DDay.iCal.Serialization.iCalendar.SerializerFactory();
            // Get a serializer for our object
            IStringSerializer serializer = factory.Build(courseCalendar.GetType(), ctx) as IStringSerializer;

            string output = serializer.SerializeToString(courseCalendar);
            var    bytes  = Encoding.UTF8.GetBytes(output);

            SaveCourseCalendar(bytes, course.ID);
        }
		/// <summary>
		/// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
		/// </summary>
		/// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
		public void ProcessRequest(HttpContext context)
		{
			var host = context.Request.Url.Host;

			// TODO: Support Filtering by date/month

			// TODO: Support filtering by category

			// initializie calendar
			var cal = new iCalendar();
			cal.Version = "1.0";

			// get events +/- 6 months
			IQueryable events;
			using (var fluent = App.WorkWith())
			{
				var center = new DateTime(year, month, 1);
				var start = center.AddMonths(-6);
				var end = center.AddMonths(6);

				events = fluent.Events().Where(e => e.EventStart >= start && e.EventEnd <= end && e.Status == Telerik.Sitefinity.GenericContent.Model.ContentLifecycleStatus.Live).Get();
			}

			foreach (Telerik.Sitefinity.Events.Model.Event ev in events)
			{
				var appt = new DDay.iCal.Event();
				appt.Start = new iCalDateTime(ev.EventStart.ToUniversalTime());
				if (ev.EventEnd.HasValue)
					appt.End = new iCalDateTime(ev.EventEnd.Value.ToUniversalTime());
				else
					appt.IsAllDay = true;

				// save and format description
				var description = ev.Content.ToString().Replace("\r\n", "<br /><br/>");
				description = description.Replace("src=\"/", "src=\"http://" + host + "/");
				appt.AddProperty("X-ALT-DESC", description);

				// non-html property
				var reg = new Regex("<(.|\n)+?>");
				appt.Description = reg.Replace(description, "");

				// event location
				var location = ev.Street;
				// location = location == null ? ev.ContentItem.GetMetaData("Street") : string.Concat(location, " (", ev.ContentItem.GetMetaData("Street"), ")");
				appt.Location = location.ToString();

				appt.Summary = ev.Title;

				// url
				//var evUrl = ConfigurationManager.AppSettings[EventsManager.DefaultContentProvider + "Url"];
				//if (string.IsNullOrEmpty(evUrl)) break;
				appt.Url = new Uri("http://www.bing.com");// string.Concat("http://", host, evUrl, ev.ContentItem.UrlWithExtension);
				cal.Events.Add(appt);
			}

			// write calendar feed!
			var ser = new iCalendarSerializer(cal);
			context.Response.Clear();
			context.Response.ContentType = "text/calendar";
			context.Response.AddHeader("content-disposition", "attachment; filename=Calendar.ics");
			context.Response.Write(ser.SerializeToString());
			//context.Response.Flush();
		}
Beispiel #46
0
        // clone the DDay.iCal event, update dtstart (and maybe dtend) with Year/Month/Day for this occurrence
        public static DDay.iCal.Event PeriodizeRecurringEvent(DDay.iCal.Event evt, IPeriod period)
        {
            var kind = evt.Start.IsUniversalTime ? DateTimeKind.Utc : DateTimeKind.Local;

            var dtstart = new DateTime(
                period.StartTime.Year,
                period.StartTime.Month,
                period.StartTime.Day,
                evt.Start.Hour,
                evt.Start.Minute,
                evt.Start.Second,
                kind);

            var idtstart = new iCalDateTime(dtstart);

            var idtend = default(iCalDateTime);
            DateTime dtend = default(DateTime);

            if (evt.DTEnd != null && evt.DTEnd.Year != 1 )
            {
                dtend = new DateTime(
                    period.EndTime.Year,
                    period.EndTime.Month,
                    period.EndTime.Day,
                    evt.End.Hour,
                    evt.End.Minute,
                    evt.End.Second,
                    kind);

                idtend = new iCalDateTime(dtend);
            }

            var instance = new DDay.iCal.Event();
            instance.Start = idtstart;
            instance.End = idtend;
            instance.Summary = evt.Summary;
            instance.Description = evt.Description;
            foreach (var cat in evt.Categories)
                instance.Categories.Add(cat);
            instance.Location = evt.Location;
            instance.GeographicLocation = evt.GeographicLocation;
            instance.UID = evt.UID;
            instance.Url = evt.Url;
            return instance;
        }
Beispiel #47
0
    public void TestUpdateResource()
    {
      uut.MakeCalendar(user, calendar);

      var theEvent = new Event();
      theEvent.Description = "bar event";
      theEvent.Start = new iCalDateTime(2000, 1, 1, 20, 0, 0);
      theEvent.End = new iCalDateTime(2000, 1, 1, 21, 0, 0);
      theEvent.Summary = "partying hard!";

      uut.CreateResource(user, calendar, theEvent);

      theEvent.Summary = "or not";
      uut.UpdateResource(user, calendar, theEvent);

      IICalendar iCal = iCalendar.LoadFromFile(calendarFile)[0];

      Assert.AreEqual(1, iCal.Events.Count);
      Assert.AreEqual(theEvent.Description, iCal.Events[0].Description);
      Assert.AreEqual(theEvent.Start, iCal.Events[0].Start);
      Assert.AreEqual(theEvent.End, iCal.Events[0].End);
      Assert.AreEqual(theEvent.Summary, iCal.Events[0].Summary);
    }
Beispiel #48
0
        /// <summary>
        /// Gets the calendar content from controls.
        /// </summary>
        /// <returns></returns>
        internal string GetCalendarContentFromControls()
        {
            EnsureChildControls();

            if ( _dpStartDateTime.SelectedDateTimeIsBlank )
            {
                return iCalendarContentEmptyEvent;
            }

            DDay.iCal.Event calendarEvent = new DDay.iCal.Event();
            calendarEvent.DTStart = new DDay.iCal.iCalDateTime( _dpStartDateTime.SelectedDateTime.Value );
            calendarEvent.DTStart.HasTime = true;

            int durationHours = TextBoxToPositiveInteger( _tbDurationHours, 0 );
            int durationMins = TextBoxToPositiveInteger( _tbDurationMinutes, 0 );

            if ( (durationHours == 0 && durationMins == 0) || this.ShowDuration == false )
            {
                // make a one second duration since a zero duration won't be included in occurrences
                calendarEvent.Duration = new TimeSpan( 0, 0, 1);
            }
            else
            {
                calendarEvent.Duration = new TimeSpan( durationHours, durationMins, 0 );
            }

            if ( _radRecurring.Checked )
            {
                if ( _radSpecificDates.Checked )
                {
                    #region specific dates
                    PeriodList recurrenceDates = new PeriodList();
                    List<string> dateStringList = _hfSpecificDateListValues.Value.Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries ).ToList();
                    foreach ( var dateString in dateStringList )
                    {
                        DateTime newDate;
                        if ( DateTime.TryParse( dateString, out newDate ) )
                        {
                            recurrenceDates.Add( new iCalDateTime( newDate.Date ) );
                        }
                    }

                    calendarEvent.RecurrenceDates.Add( recurrenceDates );
                    #endregion
                }
                else
                {
                    if ( _radDaily.Checked )
                    {
                        #region daily
                        if ( _radDailyEveryXDays.Checked )
                        {
                            RecurrencePattern rruleDaily = new RecurrencePattern( FrequencyType.Daily );

                            rruleDaily.Interval = TextBoxToPositiveInteger( _tbDailyEveryXDays );
                            calendarEvent.RecurrenceRules.Add( rruleDaily );
                        }
                        else
                        {
                            // NOTE:  Daily Every Weekday/Weekend Day is actually Weekly on Day(s)OfWeek in iCal
                            RecurrencePattern rruleWeekly = new RecurrencePattern( FrequencyType.Weekly );
                            if ( _radDailyEveryWeekday.Checked )
                            {
                                rruleWeekly.ByDay.Add( new WeekDay( DayOfWeek.Monday ) );
                                rruleWeekly.ByDay.Add( new WeekDay( DayOfWeek.Tuesday ) );
                                rruleWeekly.ByDay.Add( new WeekDay( DayOfWeek.Wednesday ) );
                                rruleWeekly.ByDay.Add( new WeekDay( DayOfWeek.Thursday ) );
                                rruleWeekly.ByDay.Add( new WeekDay( DayOfWeek.Friday ) );
                            }
                            else if ( _radDailyEveryWeekendDay.Checked )
                            {
                                rruleWeekly.ByDay.Add( new WeekDay( DayOfWeek.Saturday ) );
                                rruleWeekly.ByDay.Add( new WeekDay( DayOfWeek.Sunday ) );
                            }

                            calendarEvent.RecurrenceRules.Add( rruleWeekly );
                        }
                        #endregion
                    }
                    else if ( _radWeekly.Checked )
                    {
                        #region weekly
                        RecurrencePattern rruleWeekly = new RecurrencePattern( FrequencyType.Weekly );
                        rruleWeekly.Interval = TextBoxToPositiveInteger( _tbWeeklyEveryX );

                        if ( _cbWeeklySunday.Checked )
                        {
                            rruleWeekly.ByDay.Add( new WeekDay( DayOfWeek.Sunday ) );
                        }

                        if ( _cbWeeklyMonday.Checked )
                        {
                            rruleWeekly.ByDay.Add( new WeekDay( DayOfWeek.Monday ) );
                        }

                        if ( _cbWeeklyTuesday.Checked )
                        {
                            rruleWeekly.ByDay.Add( new WeekDay( DayOfWeek.Tuesday ) );
                        }

                        if ( _cbWeeklyWednesday.Checked )
                        {
                            rruleWeekly.ByDay.Add( new WeekDay( DayOfWeek.Wednesday ) );
                        }

                        if ( _cbWeeklyThursday.Checked )
                        {
                            rruleWeekly.ByDay.Add( new WeekDay( DayOfWeek.Thursday ) );
                        }

                        if ( _cbWeeklyFriday.Checked )
                        {
                            rruleWeekly.ByDay.Add( new WeekDay( DayOfWeek.Friday ) );
                        }

                        if ( _cbWeeklySaturday.Checked )
                        {
                            rruleWeekly.ByDay.Add( new WeekDay( DayOfWeek.Saturday ) );
                        }

                        calendarEvent.RecurrenceRules.Add( rruleWeekly );
                        #endregion
                    }
                    else if ( _radMonthly.Checked )
                    {
                        #region monthly
                        RecurrencePattern rruleMonthly = new RecurrencePattern( FrequencyType.Monthly );
                        if ( _radMonthlyDayX.Checked )
                        {
                            rruleMonthly.ByMonthDay.Add( TextBoxToPositiveInteger( _tbMonthlyDayX ) );
                            rruleMonthly.Interval = TextBoxToPositiveInteger( _tbMonthlyXMonths );
                        }
                        else if ( _radMonthlyNth.Checked )
                        {
                            WeekDay monthWeekDay = new WeekDay();
                            monthWeekDay.Offset = _ddlMonthlyNth.SelectedValue.AsIntegerOrNull() ?? 1;
                            monthWeekDay.DayOfWeek = (DayOfWeek)( _ddlMonthlyDayName.SelectedValue.AsIntegerOrNull() ?? 1 );
                            rruleMonthly.ByDay.Add( monthWeekDay );
                        }

                        calendarEvent.RecurrenceRules.Add( rruleMonthly );
                        #endregion
                    }
                }
            }

            if ( calendarEvent.RecurrenceRules.Count > 0 )
            {
                IRecurrencePattern rrule = calendarEvent.RecurrenceRules[0];

                // Continue Until
                if ( _radEndByNone.Checked )
                {
                    // intentionally blank
                }
                else if ( _radEndByDate.Checked )
                {
                    rrule.Until = _dpEndBy.SelectedDate.HasValue ? _dpEndBy.SelectedDate.Value : DateTime.MaxValue;
                }
                else if ( _radEndByOccurrenceCount.Checked )
                {
                    rrule.Count = TextBoxToPositiveInteger( _tbEndByOccurrenceCount, 0 );
                }
            }

            // Exclusions
            List<string> dateRangeStringList = _hfExclusionDateRangeListValues.Value.Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries ).ToList();

            PeriodList exceptionDates = new PeriodList();
            foreach ( string dateRangeString in dateRangeStringList )
            {
                var dateRangeParts = dateRangeString.Split( new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries );
                if ( dateRangeParts.Count() == 2 )
                {
                    DateTime beginDate;
                    DateTime endDate;

                    if ( DateTime.TryParse( dateRangeParts[0], out beginDate ) )
                    {
                        if ( DateTime.TryParse( dateRangeParts[1], out endDate ) )
                        {
                            DateTime dateToAdd = beginDate.Date;
                            while ( dateToAdd <= endDate )
                            {
                                Period periodToAdd = new Period( new iCalDateTime( dateToAdd ) );
                                if ( !exceptionDates.Contains( periodToAdd ) )
                                {
                                    exceptionDates.Add( periodToAdd );
                                }

                                dateToAdd = dateToAdd.AddDays( 1 );
                            }
                        }
                    }
                }
            }

            if ( exceptionDates.Count > 0 )
            {
                calendarEvent.ExceptionDates.Add( exceptionDates );
            }

            DDay.iCal.iCalendar calendar = new iCalendar();
            calendar.Events.Add( calendarEvent );

            iCalendarSerializer s = new iCalendarSerializer( calendar );

            return s.SerializeToString( calendar );
        }
Beispiel #49
0
        public ActionResult GetIcsForCalendar(int id)
        {
            DDay.iCal.iCalendar iCal = new DDay.iCal.iCalendar();


            var lctrl   = new LocationApiController();
            var calctrl = new CalendarApiController();
            var cal     = calctrl.GetById(id);

            EventLocation l = null;

            iCal.Properties.Add(new CalendarProperty("X-WR-CALNAME", cal.Calendarname));

            //Get normal events for calendar
            var nectrl = new EventApiController();

            foreach (var e in nectrl.GetAll().Where(x => x.calendarId == id))
            {
                // Create the event, and add it to the iCalendar
                DDay.iCal.Event evt = iCal.Create <DDay.iCal.Event>();

                var start = (DateTime)e.start;
                evt.Start = new iCalDateTime(start.ToUniversalTime());
                if (e.end != null)
                {
                    var end = (DateTime)e.end;
                    evt.End = new iCalDateTime(end.ToUniversalTime());
                }

                evt.Description = this.GetDescription(e, CultureInfo.CurrentCulture.ToString());
                evt.Summary     = e.title;
                evt.IsAllDay    = e.allDay;
                evt.Categories.AddRange(e.categories.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList());

                //If it has a location fetch it
                if (e.locationId != 0)
                {
                    l            = lctrl.GetById(e.locationId);
                    evt.Location = l.LocationName + "," + l.Street + "," + l.ZipCode + " " + l.City + "," + l.Country;
                    //evt.GeographicLocation = new GeographicLocation(Convert.ToDouble(l.lat,CultureInfo.InvariantCulture), Convert.ToDouble(l.lon, CultureInfo.InvariantCulture));
                }

                var attendes = new List <IAttendee>();

                if (e.Organisator != null && e.Organisator != 0)
                {
                    var       ms          = Services.MemberService;
                    var       member      = ms.GetById(e.Organisator);
                    string    attendee    = "MAILTO:" + member.Email;
                    IAttendee reqattendee = new DDay.iCal.Attendee(attendee)
                    {
                        CommonName = member.Name,
                        Role       = "REQ-PARTICIPANT"
                    };
                    attendes.Add(reqattendee);
                }

                if (attendes != null && attendes.Count > 0)
                {
                    evt.Attendees = attendes;
                }
            }

            //Get recurring events
            var rectrl = new REventApiController();

            foreach (var e in rectrl.GetAll().Where(x => x.calendarId == id))
            {
                // Create the event, and add it to the iCalendar
                DDay.iCal.Event evt = iCal.Create <DDay.iCal.Event>();

                evt.Description = this.GetDescription(e, CultureInfo.CurrentCulture.ToString());
                evt.Summary     = e.title;
                evt.IsAllDay    = e.allDay;
                evt.Categories.AddRange(e.categories.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList());

                //If it has a location fetch it
                if (e.locationId != 0)
                {
                    l            = lctrl.GetById(e.locationId);
                    evt.Location = l.LocationName + "," + l.Street + "," + l.ZipCode + " " + l.City + "," + l.Country;
                    //evt.GeographicLocation = new GeographicLocation(Convert.ToDouble(l.lat, CultureInfo.InvariantCulture), Convert.ToDouble(l.lon, CultureInfo.InvariantCulture));
                }

                RecurrencePattern rp = null;
                var frequency        = (FrequencyTypeEnum)e.frequency;
                switch (frequency)
                {
                case FrequencyTypeEnum.Daily:
                {
                    rp = new RecurrencePattern(FrequencyType.Daily);
                    break;
                }

                case FrequencyTypeEnum.Monthly:
                {
                    rp = new RecurrencePattern(FrequencyType.Monthly);
                    break;
                }

                case FrequencyTypeEnum.Weekly:
                {
                    rp = new RecurrencePattern(FrequencyType.Weekly);
                    break;
                }

                case FrequencyTypeEnum.Yearly:
                {
                    rp = new RecurrencePattern(FrequencyType.Yearly);
                    break;
                }

                default:
                {
                    rp = new RecurrencePattern(FrequencyType.Monthly);
                    break;
                }
                }
                switch (e.day)
                {
                case (int)DayOfWeekEnum.Mon:
                {
                    rp.ByDay.Add(new WeekDay(DayOfWeek.Monday));
                    break;
                }

                case (int)DayOfWeekEnum.Tue:
                {
                    rp.ByDay.Add(new WeekDay(DayOfWeek.Tuesday));
                    break;
                }

                case (int)DayOfWeekEnum.Wed:
                {
                    rp.ByDay.Add(new WeekDay(DayOfWeek.Wednesday));
                    break;
                }

                case (int)DayOfWeekEnum.Thu:
                {
                    rp.ByDay.Add(new WeekDay(DayOfWeek.Thursday));
                    break;
                }

                case (int)DayOfWeekEnum.Fri:
                {
                    rp.ByDay.Add(new WeekDay(DayOfWeek.Friday));
                    break;
                }

                case (int)DayOfWeekEnum.Sat:
                {
                    rp.ByDay.Add(new WeekDay(DayOfWeek.Saturday));
                    break;
                }

                case (int)DayOfWeekEnum.Sun:
                {
                    rp.ByDay.Add(new WeekDay(DayOfWeek.Sunday));
                    break;
                }
                }
                evt.RecurrenceRules.Add(rp);

                Schedule schedule = new Schedule(new ScheduleWidget.ScheduledEvents.Event()
                {
                    Title                  = e.title,
                    DaysOfWeekOptions      = (DayOfWeekEnum)e.day,
                    FrequencyTypeOptions   = (FrequencyTypeEnum)e.frequency,
                    MonthlyIntervalOptions = (MonthlyIntervalEnum)e.monthly_interval
                });

                var occurence = Convert.ToDateTime(schedule.NextOccurrence(DateTime.Now));
                evt.Start = new iCalDateTime(new DateTime(occurence.Year, occurence.Month, occurence.Day, e.start.Hour, e.start.Minute, 0));

                var attendes = new List <IAttendee>();

                if (e.Organisator != null && e.Organisator != 0)
                {
                    var       ms          = Services.MemberService;
                    var       member      = ms.GetById(e.Organisator);
                    string    attendee    = "MAILTO:" + member.Email;
                    IAttendee reqattendee = new DDay.iCal.Attendee(attendee)
                    {
                        CommonName = member.Name,
                        Role       = "REQ-PARTICIPANT"
                    };
                    attendes.Add(reqattendee);
                }

                if (attendes != null && attendes.Count > 0)
                {
                    evt.Attendees = attendes;
                }
            }

            // Create a serialization context and serializer factory.
            // These will be used to build the serializer for our object.
            ISerializationContext ctx     = new SerializationContext();
            ISerializerFactory    factory = new DDay.iCal.Serialization.iCalendar.SerializerFactory();
            // Get a serializer for our object
            IStringSerializer serializer = factory.Build(iCal.GetType(), ctx) as IStringSerializer;

            string output      = serializer.SerializeToString(iCal);
            var    contentType = "text/calendar";
            var    bytes       = Encoding.UTF8.GetBytes(output);

            return(File(bytes, contentType, cal.Calendarname + ".ics"));
        }