Exemple #1
1
        static void Main(string[] args)
        {
            // Create a new calendar
            IICalendar iCal = new iCalendar();

            // Add the local time zone to the calendar
            ITimeZone local = iCal.AddLocalTimeZone();

            // Build a list of additional time zones
            // from .NET Framework.
            List<ITimeZone> otherTimeZones = new List<ITimeZone>();                        
            foreach (TimeZoneInfo tzi in System.TimeZoneInfo.GetSystemTimeZones())
            {
                // We've already added the local time zone, so let's skip it!
                if (tzi != System.TimeZoneInfo.Local)
                {
                    // Add the time zone to our list (but don't include it directly in the calendar).
                    otherTimeZones.Add(iCalTimeZone.FromSystemTimeZone(tzi));
                }
            }

            // Create a new event in the calendar
            // that uses our local time zone
            IEvent evt = iCal.Create<Event>();
            evt.Summary = "Test Event";
            evt.Start = iCalDateTime.Today.AddHours(8).SetTimeZone(local);            
            evt.Duration = TimeSpan.FromHours(1);

            // Get all occurrences of the event that happen today
            foreach (Occurrence occurrence in iCal.GetOccurrences<IEvent>(iCalDateTime.Today))
            {
                // Write the event with the time zone information attached
                Console.WriteLine(occurrence.Period.StartTime);

                // Note that the time printed is identical to the above, but without time zone information.
                Console.WriteLine(occurrence.Period.StartTime.Local);

                // Convert the start time to other time zones and display the relative time.
                foreach (ITimeZone otherTimeZone in otherTimeZones)
                    Console.WriteLine(occurrence.Period.StartTime.ToTimeZone(otherTimeZone));
            }
        }
        public override iCalObject Deserialize(TextReader tr, Type iCalendarType)
        {
            // Normalize line endings, so "\r" is treated the same as "\r\n"
            // NOTE: fixed bug #1773194 - Some applications emit mixed line endings
            TextReader textReader = NormalizeLineEndings(tr);

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

            // Determine the calendar type we'll be using when constructing
            // iCalendar objects...
            parser.iCalendarType = iCalendarType;

            // Parse the component!
            DDay.iCal.iCalendar iCal      = new DDay.iCal.iCalendar();
            iCalObject          component = parser.component(iCal);

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

            // Return the parsed component
            return(component);
        }
        public void ExportSolution()
        {
            DDay.iCal.iCalendar iCal = new DDay.iCal.iCalendar();
            var t = new DBManager();
            t.initInputData();
            t.initOutputData();
            foreach(ScheduledTimeSlot[] solution in (t.solutions))
            {
                for (int i = 0; i < solution.Length; i++)
                {
                    Event evt = iCal.Create<Event>();

                    evt.Start = iCalDateTime.Today.AddHours((int)solution[i].timeSlot.StartHour).AddDays((int)(solution[i].timeSlot.Day));

                    evt.End = iCalDateTime.Today.AddHours((int)solution[i].timeSlot.EndHour).AddDays((int)(solution[i].timeSlot.Day));

                    evt.Summary = string.Join(", ", solution[i].groups.Select(g => g.name));

                    evt.Location = solution[i].room.nameOrNumber;
                }
                break;
            }

            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 bytes = Encoding.UTF8.GetBytes(output);

            File.WriteAllBytes("solution.ics", bytes);
        }
        // GET: Calendar
        public ActionResult Index()
        {
            foreach (var r in Request.Params.AllKeys)
            {
                System.Diagnostics.Debug.WriteLine(r + " = " + Request.Params[r]);
            }

            var iCal = new iCalendar();

            Event evt = iCal.Create<Event>();
            evt.Start = iCalDateTime.Today.AddHours(8);
            evt.End = evt.Start.AddHours(18); // This also sets the duration
            evt.Description = "The event description";
            evt.Location = "Event location";
            evt.Summary = "18 hour event summary";
            
            evt = iCal.Create<Event>();
            evt.Start = iCalDateTime.Today.AddDays(5);
            evt.End = evt.Start.AddDays(1);
            evt.IsAllDay = true;
            evt.Summary = "All-day event";

            ISerializationContext ctx = new SerializationContext();
            ISerializerFactory factory = new DDay.iCal.Serialization.iCalendar.SerializerFactory();
            IStringSerializer serializer = factory.Build(iCal.GetType(), ctx) as IStringSerializer;

            string output = serializer.SerializeToString(iCal);
            var bytes = System.Text.Encoding.UTF8.GetBytes(output);

            return File(bytes, "text/calendar");
        }
        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));
        }
Exemple #6
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();
        }
Exemple #7
0
        public ActionResult Calendar()
        {
            DDay.iCal.iCalendar iCal = new DDay.iCal.iCalendar();

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

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

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

            // 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, "calendar.ics"));
        }
Exemple #8
0
 private static void SaveToFile(string icsFilename, iCalendar ical) {
     var ctx = new SerializationContext();
     var factory = new SerializerFactory();
     var serializer = factory.Build(ical.GetType(), ctx) as IStringSerializer;
     var content = serializer.SerializeToString(ical);
     File.WriteAllText(icsFilename, content);
 }
Exemple #9
0
        private System.IO.MemoryStream Generacion(string Titulo, String nombreCalendario, DateTime fechayHoraInicio, Int32 duracionEnMinutos, string ubicacion)
        {
            DDay.iCal.iCalendar iCal = new DDay.iCal.iCalendar();
            // Create the event, and add it to the iCalendar
            Event evt = iCal.Create <Event>();

            // Set information about the event
            evt.Start       = new iCalDateTime(fechayHoraInicio);
            evt.End         = evt.Start.AddMinutes(duracionEnMinutos); // This also sets the duration
            evt.Description = String.Format("Agenda del día {0} a las {1}",
                                            fechayHoraInicio.ToString("dd 'de' MMM 'de' yyyy"),
                                            fechayHoraInicio.ToString("HH:MM")
                                            );
            evt.Location = ubicacion;
            evt.Summary  = Titulo;
            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 bytes = Encoding.UTF8.GetBytes(output);

            //return File(bytes, contentType, DownloadFileName);
            System.IO.MemoryStream data = new System.IO.MemoryStream(bytes);
            return(data);
        }
Exemple #10
0
    private Calendar(string filePath)
    {
      _filePath = filePath;
      lock(fileLock)
      {
        _calendar = iCalendar.LoadFromStream(File.OpenRead(filePath)).FirstOrDefault() as iCalendar;

        _items = _calendar
          .GetOccurrences(new iCalDateTime(DateTime.Now), new iCalDateTime(DateTime.Now.AddYears(1)))
          .Select(o =>
            new CalendarItem()
            {
              What = (o.Source as Event).Summary,
              Where = (o.Source as Event).Location,
              When = new iCalDateTime( 
                o.Period.StartTime.Year, 
                o.Period.StartTime.Month,
                o.Period.StartTime.Day,
                o.Period.StartTime.Hour,
                o.Period.StartTime.Minute,
                o.Period.StartTime.Second,
                "Europe/Amsterdam") // make sure that our timezone is correct
            })
           .ToList();
      }
    }
Exemple #11
0
        public void CreateEntry(string summary, DateTime date, string icsFilename) {
            var ical = new iCalendar();
            var ev = ical.Create<Event>();
            ev.Summary = summary;
            ev.Start = new iCalDateTime(date);

            SaveToFile(icsFilename, ical);
        }
Exemple #12
0
        private Response GetCalendarFeed()
        {
            var pastDays = 7;
            var futureDays = 28;            
            var start = DateTime.Today.AddDays(-pastDays);
            var end = DateTime.Today.AddDays(futureDays);

            // TODO: Remove start/end parameters in v3, they don't work well for iCal
            var queryStart = Request.Query.Start;
            var queryEnd = Request.Query.End;
            var queryPastDays = Request.Query.PastDays;
            var queryFutureDays = Request.Query.FutureDays;

            if (queryStart.HasValue) start = DateTime.Parse(queryStart.Value);
            if (queryEnd.HasValue) end = DateTime.Parse(queryEnd.Value);

            if (queryPastDays.HasValue)
            {
                pastDays = int.Parse(queryPastDays.Value);
                start = DateTime.Today.AddDays(-pastDays);
            }

            if (queryFutureDays.HasValue)
            {
                futureDays = int.Parse(queryFutureDays.Value);
                end = DateTime.Today.AddDays(futureDays);
            }

            var episodes = _episodeService.EpisodesBetweenDates(start, end, false);
            var icalCalendar = new iCalendar();

            foreach (var episode in episodes.OrderBy(v => v.AirDateUtc.Value))
            {
                var occurrence = icalCalendar.Create<Event>();
                occurrence.UID = "NzbDrone_episode_" + episode.Id.ToString();
                occurrence.Status = episode.HasFile ? EventStatus.Confirmed : EventStatus.Tentative;
                occurrence.Start = new iCalDateTime(episode.AirDateUtc.Value) { HasTime = true };
                occurrence.End = new iCalDateTime(episode.AirDateUtc.Value.AddMinutes(episode.Series.Runtime)) { HasTime = true };
                occurrence.Description = episode.Overview;
                occurrence.Categories = new List<string>() { episode.Series.Network };

                switch (episode.Series.SeriesType)
                {
                    case SeriesTypes.Daily:
                        occurrence.Summary = string.Format("{0} - {1}", episode.Series.Title, episode.Title);
                        break;

                    default:
                        occurrence.Summary = string.Format("{0} - {1}x{2:00} - {3}", episode.Series.Title, episode.SeasonNumber, episode.EpisodeNumber, episode.Title);
                        break;
                }
            }

            var serializer = new DDay.iCal.Serialization.iCalendar.SerializerFactory().Build(icalCalendar.GetType(), new DDay.iCal.Serialization.SerializationContext()) as DDay.iCal.Serialization.IStringSerializer;
            var icalendar = serializer.SerializeToString(icalCalendar);

            return new TextResponse(icalendar, "text/calendar");
        }
Exemple #13
0
 private void Schedule_Load(object sender, EventArgs e)
 {
     iCal = iCalendar.LoadFromFile(@"Calendars\USHolidays.ics");
     iCal.MergeWith(iCalendar.LoadFromFile(@"Calendars\lotr.ics"));
     iCal.MergeWith(iCalendar.LoadFromFile(@"Calendars\To-do.ics"));
     //iCal.MergeWith(iCalendar.LoadFromFile("Barça 2006 - 2007.ics"));
     if (iCal == null)
         throw new ApplicationException("iCalendar could not be loaded.");
 }
Exemple #14
0
        public void CreateEntry(string summary, string description, DateTime start, DateTime end, string icsFilename) {
            var ical = new iCalendar();
            var ev = ical.Create<Event>();
            ev.Summary = summary;
            ev.Description = description;
            ev.Start = new iCalDateTime(start);
            ev.End = new iCalDateTime(end);

            SaveToFile(icsFilename, ical);
        }
Exemple #15
0
        private static void HillsideExampleIsCorrectIcs(DDay.iCal.iCalendar ical)
        {
            Assert.That(ical.Events.Count > 0);              // it's a recurring event, don't need/want to test for exact count
            var evt = ical.Events[0];

            Assert.That(evt.Summary.StartsWith("Afternoon Tea 3"));
            Assert.That(evt.Start.Hour == 15);
            Assert.That(evt.Start.Minute == 0);
            Assert.That(evt.Start.Second == 0);
        }
Exemple #16
0
 protected bool Equals(iCalendar other)
 {
     return(base.Equals(other) &&
            Equals(m_UniqueComponents, other.m_UniqueComponents) &&
            Equals(m_Events, other.m_Events) &&
            Equals(m_Todos, other.m_Todos) &&
            Equals(m_Journals, other.m_Journals) &&
            Equals(m_FreeBusy, other.m_FreeBusy) &&
            Equals(m_TimeZones, other.m_TimeZones));
 }
		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();
		}
Exemple #18
0
        /// <summary>
        /// Appends the episode to an iCalendar calendar
        /// </summary>
        /// <param name="ical">The iCalendar to append to</param>
        public void CreateEventFromEpisode(iCalendar ical, int offset)
        {
            Event e = ical.Create<Event>();

            iCalDateTime offsetDate = (iCalDateTime)date.AddHours(offset);

            e.Start = offsetDate;
            e.End = offsetDate.AddHours(1);
            e.Summary = seriesTitle;
            e.Description = episodeTitle;
        }
Exemple #19
0
        //public ArrayList GetTodos(string category)
        //{
        //    ArrayList t = new ArrayList();
        //    foreach (Todo todo in Todos)
        //    {
        //        if (todo.Categories != null)
        //        {
        //            foreach (TextCollection cat in todo.Categories)
        //            {
        //                foreach (Text text in cat.Values)
        //                {
        //                    if (text.Value == category)
        //                        t.Add(todo);
        //                }
        //            }
        //        }
        //    }

        //    return t;
        //}

        /// <summary>
        /// Merges the current <see cref="iCalendar"/> with another iCalendar.
        /// <note>
        ///     Since each object is associated with one and only one iCalendar object,
        ///     the <paramref name="iCal"/> that is passed is automatically Disposed
        ///     in the process, because all of its objects are re-assocated with the new iCalendar.
        /// </note>
        /// </summary>
        /// <param name="iCal">The iCalendar to merge with the current <see cref="iCalendar"/></param>
        public void MergeWith(iCalendar iCal)
        {
            if (iCal != null)
            {
                foreach (iCalObject obj in iCal.Children)
                {
                    this.AddChild(obj);
                }
                iCal.Dispose();
            }
        }
Exemple #20
0
        //public ArrayList GetTodos(string category)
        //{
        //    ArrayList t = new ArrayList();
        //    foreach (Todo todo in Todos)
        //    {
        //        if (todo.Categories != null)
        //        {
        //            foreach (TextCollection cat in todo.Categories)
        //            {
        //                foreach (Text text in cat.Values)
        //                {
        //                    if (text.Value == category)
        //                        t.Add(todo);
        //                }
        //            }
        //        }
        //    }

        //    return t;
        //}

        /// <summary>
        /// Merges the current <see cref="iCalendar"/> with another iCalendar.
        /// <note>
        ///     Since each object is associated with one and only one iCalendar object,
        ///     the <paramref name="iCal"/> that is passed is automatically Disposed
        ///     in the process, because all of its objects are re-assocated with the new iCalendar.
        /// </note>
        /// </summary>
        /// <param name="iCal">The iCalendar to merge with the current <see cref="iCalendar"/></param>
        public void MergeWith(iCalendar iCal)
        {
            if (iCal != null)
            {
                foreach (UniqueComponent uc in iCal.UniqueComponents)
                {
                    this.AddChild(uc);
                }
                iCal.Dispose();
            }
        }
Exemple #21
0
        public void icalbody(
            iCalendar iCal
            ) //throws RecognitionException, TokenStreamException
        {
            {
                switch (LA(1))
                {
                case IANA_TOKEN:
                case X_NAME:
                case PRODID:
                case VERSION:
                case CALSCALE:
                case METHOD:
                {
                    calprops(iCal);
                    break;
                }

                case BEGIN:
                case END:
                {
                    break;
                }

                default:
                {
                    throw new NoViableAltException(LT(1), getFilename());
                }
                }
            }
            {
                switch (LA(1))
                {
                case BEGIN:
                {
                    component(iCal);
                    break;
                }

                case END:
                {
                    break;
                }

                default:
                {
                    throw new NoViableAltException(LT(1), getFilename());
                }
                }
            }
        }
Exemple #22
0
        /// <summary>
        /// Merges the current <see cref="iCalendar"/> with another iCalendar.
        /// <note>
        ///     Since each object is associated with one and only one iCalendar object,
        ///     the <paramref name="iCal"/> that is passed is automatically Disposed
        ///     in the process, because all of its objects are re-assocated with the new iCalendar.
        /// </note>
        /// </summary>
        /// <param name="iCal">The iCalendar to merge with the current <see cref="iCalendar"/></param>
        public void MergeWith(iCalendar iCal)
        {
            if (iCal != null)
            {
                // Merge all unique components
                foreach (UniqueComponent uc in iCal.UniqueComponents)
                {
                    this.AddChild(uc);
                }

                // Dispose of the calendar, since we just siphoned the components from it.
                iCal.Dispose();
            }
        }
Exemple #23
0
        public void Convert(DDay.iCal.iCalendar iCalendar, Stream s)
        {
            xCalWriter writer = new xCalWriter(s, Encoding.UTF8);

            writer.WriteStartElement("icalendar", xCalWriter.iCalendar20Namespace);

            WriteComponent(iCalendar, writer);

            writer.WriteEndDocument();

            writer.Close();

            writer.Dispose();
        }
 public static Event DinnerToEvent(Dinner dinner, iCalendar iCal)
 {
     string eventLink = "http://nrddnr.com/" + dinner.DinnerID;
     Event evt = iCal.Create<Event>();
     evt.Start = 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.AddContact(dinner.ContactPhone);
     evt.Geo = new Geo(dinner.Latitude, dinner.Longitude);
     evt.Url = eventLink;
     evt.Description = eventLink;
     return evt;
 }
Exemple #25
0
 public void icalbody(
     iCalendar iCal
     )     //throws RecognitionException, TokenStreamException
 {
     try { // for error handling
         calprops(iCal);
         component(iCal);
     }
     catch (RecognitionException ex)
     {
         reportError(ex);
         recover(ex, tokenSet_1_);
     }
 }
        public DDayCalendarWriter(iCalendar iCal, TextWriter writer)
        {
            if (iCal == null)
            {
                throw new ArgumentNullException("iCal");
            }

            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }

            _ical = iCal;
            _writer = writer;
        }
Exemple #27
0
        private static bool ParseFails(string feedtext, DDay.iCal.iCalendar ical)
        {
            StringReader sr;

            try
            {
                sr   = new StringReader(feedtext);
                ical = (DDay.iCal.iCalendar)iCalendar.LoadFromStream(sr).FirstOrDefault().iCalendar;
            }
            catch
            {
                Assert.IsNull(ical);
                return(true);
            }
            return(false);
        }
    public ActionResult TeamFeed(int seasonId, int teamId, string desc)
    {

      var seasonName = _context.Seasons.Where(x => x.SeasonId == seasonId).Single().SeasonName;
      var teamName = _context.Teams.Where(x => x.TeamId == teamId).Single().TeamNameLong;

      List<GameTeam> gameTeams = _context.GameTeams
                              .IncludeAll()
                              .Where(x => x.SeasonId == seasonId && x.TeamId == teamId)
                              .ToList();

      iCalendar ical = new iCalendar();
      ical.Properties.Set("X-WR-CALNAME", "LO30Schedule-" + teamName.Replace(" ", "") + "-" + seasonName.Replace(" ", ""));
      foreach (var gameTeam in gameTeams)
      {
        Event icalEvent = ical.Create<Event>();

        var summary = gameTeam.OpponentTeam.TeamNameShort + " vs " + gameTeam.Team.TeamNameShort;
        if (gameTeam.HomeTeam)
        {
          summary = gameTeam.Team.TeamNameShort + " vs " + gameTeam.OpponentTeam.TeamNameShort;
        }

        icalEvent.Summary = summary;
        icalEvent.Description = summary + " " + gameTeam.Game.Location;

        var year = gameTeam.Game.GameDateTime.Year;
        var mon = gameTeam.Game.GameDateTime.Month;
        var day = gameTeam.Game.GameDateTime.Day;
        var hr = gameTeam.Game.GameDateTime.Hour;
        var min = gameTeam.Game.GameDateTime.Minute;
        var sec = gameTeam.Game.GameDateTime.Second;
        icalEvent.Start = new iCalDateTime(gameTeam.Game.GameDateTime);
        icalEvent.Duration = TimeSpan.FromHours(1.25);
        //icalEvent.Location = "Eddie Edgar " + gameTeam.Game.Location;  // TODO set the Rink location
        icalEvent.Location = "Eddie Edgar";
      }

      ISerializationContext ctx = new SerializationContext();
      ISerializerFactory factory = new SerializerFactory();
      IStringSerializer serializer = factory.Build(ical.GetType(), ctx) as IStringSerializer;

      string output = serializer.SerializeToString(ical);
      var contentType = "text/calendar";

      return Content(output, contentType);
    }
Exemple #29
0
        public iCalendar  icalobject() //throws RecognitionException, TokenStreamException
        {
            iCalendar iCal = new iCalendar();;


            try {         // for error handling
                {         // ( ... )+
                    int _cnt3 = 0;
                    for (;;)
                    {
                        if ((LA(1) == BEGIN))
                        {
                            match(BEGIN);
                            match(COLON);
                            match(VCALENDAR);
                            match(CRLF);
                            icalbody(iCal);
                            match(END);
                            match(COLON);
                            match(VCALENDAR);
                            match(CRLF);
                        }
                        else
                        {
                            if (_cnt3 >= 1)
                            {
                                goto _loop3_breakloop;
                            }
                            else
                            {
                                throw new NoViableAltException(LT(1), getFilename());;
                            }
                        }

                        _cnt3++;
                    }
                    _loop3_breakloop :;
                }            // ( ... )+
                iCal.OnLoad(EventArgs.Empty);
            }
            catch (RecognitionException ex)
            {
                reportError(ex);
                recover(ex, tokenSet_0_);
            }
            return(iCal);
        }
Exemple #30
0
        /// <summary>
        /// Merges the current <see cref="iCalendar"/> with another iCalendar.
        /// <note>
        ///     Since each object is associated with one and only one iCalendar object,
        ///     the <paramref name="iCal"/> that is passed is automatically Disposed
        ///     in the process, because all of its objects are re-assocated with the new iCalendar.
        /// </note>
        /// </summary>
        /// <param name="iCal">The iCalendar to merge with the current <see cref="iCalendar"/></param>
        public void MergeWith(iCalendar iCal)
        {
            if (iCal != null)
            {
                // Merge all parameters
                foreach (Parameter p in iCal.Parameters)
                {
                    if (!Parameters.ContainsKey(p.Key))
                    {
                        AddParameter(p);
                    }
                }

                // Merge all properties
                foreach (Property p in iCal.Properties)
                {
                    if (!Properties.ContainsKey(p.Key))
                    {
                        AddProperty(p);
                    }
                }

                // Merge all unique components
                foreach (UniqueComponent uc in iCal.UniqueComponents)
                {
                    if (!this.UniqueComponents.ContainsKey(uc.UID))
                    {
                        this.AddChild(uc);
                    }
                }

                // Add all time zones
                foreach (iCalTimeZone tz in iCal.TimeZones)
                {
                    // Only add the time zone if it doesn't already exist
                    if (this.GetTimeZone(tz.TZID) == null)
                    {
                        this.AddChild(tz);
                    }
                }

                // Dispose of the calendar, since we just siphoned the components from it.
                iCal.Dispose();
            }
        }
        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));
        }
Exemple #32
0
        static public iCalendar LoadFromStream(Type iCalendarType, TextReader tr)
        {
            // Create a lexer for our text stream
            iCalLexer  lexer  = new iCalLexer(tr);
            iCalParser parser = new iCalParser(lexer);

            // Determine the calendar type we'll be using when constructing
            // iCalendar objects...
            parser.iCalendarType = iCalendarType;

            // Parse the iCalendar!
            iCalendar iCal = parser.icalobject();

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

            // Return the parsed iCalendar
            return(iCal);
        }
Exemple #33
0
        /// <summary>
        /// The main program execution.
        /// </summary>
        static void Main(string[] args)
        {
            // Create a new iCalendar
            iCalendar iCal = new iCalendar();
            
            // Create the event, and add it to the iCalendar
            Event evt = iCal.Create<Event>();

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

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

            // Display each event
            foreach(Event e in iCal.Events)
                Console.WriteLine("Event created: " + GetDescription(e));
            
            // Serialize (save) the iCalendar
            iCalendarSerializer serializer = new iCalendarSerializer();
            serializer.Serialize(iCal, @"iCalendar.ics");
            Console.WriteLine("iCalendar file saved." + Environment.NewLine);
            
            // Load the calendar from the file we just saved
            IICalendarCollection calendars = iCalendar.LoadFromFile(@"iCalendar.ics");
            Console.WriteLine("iCalendar file loaded.");

            // Iterate through each event to display its description
            // (and verify the file saved correctly)
            foreach (IICalendar calendar in calendars)
            {
                foreach (IEvent e in calendar.Events)
                    Console.WriteLine("Event loaded: " + GetDescription(e));
            }
        }
Exemple #34
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));
        }
        // From: http://sourcefield.blogspot.com/2011/06/dday-ical-example.html
        public void Example()
        {
            // #1: Monthly meetings that occur on the last Wednesday from 6pm - 7pm

            // Create an iCalendar
            var iCal = new iCalendar();

            // Create the event
            var evt = iCal.Create<Event>();
            evt.Summary = "Test Event";
            evt.Start = new iCalDateTime(2008, 1, 1, 18, 0, 0); // Starts January 1, 2008 @ 6:00 P.M.
            evt.Duration = TimeSpan.FromHours(1);

            // Add a recurrence pattern to the event
            var rp = new RecurrencePattern {Frequency = FrequencyType.Monthly};
            rp.ByDay.Add(new WeekDay(DayOfWeek.Wednesday, FrequencyOccurrence.Last));
            evt.RecurrenceRules.Add(rp);

            // #2: Yearly events like holidays that occur on the same day each year.
            // The same as #1, except:
            var rp2 = new RecurrencePattern {Frequency = FrequencyType.Yearly};
            evt.RecurrenceRules.Add(rp2);

            // #3: Yearly events like holidays that occur on a specific day like the first monday.
            // The same as #1, except:
            var rp3 = new RecurrencePattern {Frequency = FrequencyType.Yearly};
            rp3.ByMonth.Add(3);
            rp3.ByDay.Add(new WeekDay(DayOfWeek.Monday, FrequencyOccurrence.First));
            evt.RecurrenceRules.Add(rp3);

            /*
            Note that all events occur on their start time, no matter their
            recurrence pattern. So, for example, you could occur on the first Monday
            of every month, but if your event is scheduled for a Friday (i.e.
            evt.Start = new iCalDateTime(2008, 3, 7, 18, 0, 0)), then it will first
            occur on that Friday, and then the first Monday of every month after
            that.

             this can be worked around by doing this:
             IPeriod nextOccurrence = pattern.GetNextOccurrence(dt);
             evt.Start = nextOccurrence.StartTime;
             */
        }
Exemple #36
0
        static void Main(string[] args)
        {
            Login login = new Login();

            var showtimeline = login.GetEpisodeNodes("stufkan", "stufkan", ScheduleTypeEnum.upcoming);

            iCalendar ical = new iCalendar();

            foreach (var item in showtimeline)
            {
                ExtractNode.Extract(item).CreateEventFromEpisode(ical,33);
            }

            iCalendarSerializer serializer = new iCalendarSerializer();
            serializer.Serialize(ical, @"showRss.ics");

            Console.WriteLine("Done");
            Console.ReadKey();
        }
Exemple #37
0
        public void FeedOnlyParsesWhenAllProblemsRepaired()
        {
            var feedtext = @"BEGIN:VCALENDAR
METHOD:PUBLISH
PRODID:-//192.168.100.199//NONSGML iCalcreator 2.4.3//
VERSION:2.0
X-WR-CALNAME:AADL Events
X-WR-CALDESC:Ann Arbor District Library Calendar
X-WR-TIMEZONE:US/Eastern
BEGIN:VEVENT
DESCRIPTION
DTEND:20120508T160000
DTSTART:20120508T150000
LOCATION:Downtown Library: 4th Floor Meeting Room\, 343 South Fifth Avenue\
 , Ann Arbor\, Michigan 48104
SUMMARY:Neil Bernstein\, NLS Research & Development Officer
END:VEVENT
BEGIN:VEVENT
UID:[email protected]
DTSTAMP:20120912T134429Z
LOCATION:Downtown Library: 4th Floor Meeting Room\, 343 South Fifth Avenue\, 
Ann Arbor\, Michigan 48104
SUMMARY:Microsoft Publisher
END:VEVENT
END:VCALENDAR";

            StringReader sr;

            DDay.iCal.iCalendar ical = null;

            Assert.That(ParseFails(feedtext, ical));

            feedtext = Utils.FixMiswrappedComponent(feedtext, "LOCATION");

            Assert.That(ParseFails(feedtext, ical));

            feedtext = Utils.AddColonToBarePropnames(feedtext);

            sr   = new StringReader(feedtext);
            ical = (DDay.iCal.iCalendar)iCalendar.LoadFromStream(sr).FirstOrDefault().iCalendar;
            Assert.That(ical.Events.Count > 0);
        }
Exemple #38
0
        static void Main(string[] args)
        {
            // Create a new iCalendar
            iCalendar iCal = new iCalendar();
            
            // Create the event, and add it to the iCalendar
            Event evt = Event.Create(iCal);

            // Set information about the event
            evt.Start = DateTime.Today;
            evt.End = DateTime.Today.AddDays(1); // This also sets the duration
            evt.DTStamp = DateTime.Now;
            evt.Description = "The event description";
            evt.Location = "Event location";
            evt.Summary = "The summary of the event";
            
            // Serialize (save) the iCalendar
            iCalendarSerializer serializer = new iCalendarSerializer(iCal);
            serializer.Serialize(@"iCalendar.ics");
        }
        public override iCalObject Deserialize(TextReader tr, Type iCalendarType)
        {
            // Create a lexer for our text stream
            iCalLexer  lexer  = new iCalLexer(tr);
            iCalParser parser = new iCalParser(lexer);

            // Determine the calendar type we'll be using when constructing
            // iCalendar objects...
            parser.iCalendarType = iCalendarType;

            // Parse the component!
            DDay.iCal.iCalendar iCal      = new DDay.iCal.iCalendar();
            iCalObject          component = parser.component(iCal);

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

            // Return the parsed component
            return(component);
        }
Exemple #40
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);
        }
        public ActionResult ExportSolution()
        {
            var userDetail = SessionHelper.GetUserDetailFromSession();

            if (userDetail == null)
            {
                return(RedirectToAction("Index", "Login", new { ReturnUrl = "/BookRoom" }));
            }
            int UserId         = Convert.ToInt32(userDetail.user.id);
            var calendarevents = db.BookRooms.Where(x => x.UserId == UserId && x.IsSyncIcal == false && x.IsActive == true).ToList();
            // var calendarevents = CM.calendardetailtomodel();
            var FileTime = DateTime.Now.ToFileTime();
            var ext      = ".ics";

            DDay.iCal.iCalendar iCal = new DDay.iCal.iCalendar();
            foreach (var demoEvent in calendarevents)
            {
                Event evt = iCal.Create <Event>();
                evt.Start       = new iCalDateTime(demoEvent.StartDate);
                evt.End         = new iCalDateTime(demoEvent.EndDate);
                evt.Description = demoEvent.Description;
                evt.Summary     = demoEvent.Description;
                var datas = db.BookRooms.Where(x => x.BookRoomId == demoEvent.BookRoomId).FirstOrDefault();
                if (datas != null)
                {
                    datas.IsSyncIcal = true;
                    db.SaveChanges();//update
                    //TempData["StatusMsg"] = "Success";
                }
            }
            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, FileTime + ext));
        }
Exemple #42
0
        /// <summary>
        /// The main program execution.
        /// </summary>
        static void Main(string[] args)
        {
            // Create a new iCalendar
            iCalendar iCal = new iCalendar();
            
            // Create the event, and add it to the iCalendar
            Event evt = Event.Create(iCal);

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

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

            // Display each event
            foreach(Event e in iCal.Events)
                Console.WriteLine("Event created: " + GetDescription(e));
            
            // Serialize (save) the iCalendar
            iCalendarSerializer serializer = new iCalendarSerializer(iCal);
            serializer.Serialize(@"iCalendar.ics");
            Console.WriteLine("iCalendar file saved." + Environment.NewLine);
            
            iCal = iCalendar.LoadFromFile(@"iCalendar.ics");
            Console.WriteLine("iCalendar file loaded.");
            foreach (Event e in iCal.Events)
                Console.WriteLine("Event loaded: " + GetDescription(e));
        }
        protected override void WriteFile(System.Web.HttpResponseBase response)
        {
            iCalendar iCal = new iCalendar();

            var evnt = iCal.Create<Event>();

            evnt.Summary = _info.Name;
            evnt.Start = new iCalDateTime(_info.StartDate);
            evnt.Duration = _info.Duration;
            evnt.GeographicLocation = _info.Geo;
            evnt.Location = _info.Location;
            evnt.Url = new Uri(_info.Url);

            //iCal.Events.Add(evnt);

            var ser = new iCalendarSerializer();
            string result = ser.SerializeToString(iCal);
            //iCalendarSerializer serializer = new iCalendarSerializer(iCal);
            //string result = serializer.SerializeToString();
            response.ContentEncoding = Encoding.UTF8;
            response.Write(result);
        }
Exemple #44
0
        public void calprops(
            iCalendar iCal
            )     //throws RecognitionException, TokenStreamException
        {
            try { // for error handling
                calprop(iCal);
                { // ( ... )+
                    int _cnt16 = 0;
                    for (;;)
                    {
                        if ((tokenSet_2_.member(LA(1))))
                        {
                            calprop(iCal);
                        }
                        else
                        {
                            if (_cnt16 >= 1)
                            {
                                goto _loop16_breakloop;
                            }
                            else
                            {
                                throw new NoViableAltException(LT(1), getFilename());;
                            }
                        }

                        _cnt16++;
                    }
                    _loop16_breakloop :;
                }            // ( ... )+
            }
            catch (RecognitionException ex)
            {
                reportError(ex);
                recover(ex, tokenSet_3_);
            }
        }
Exemple #45
0
        public iCalendar  icalobject() //throws RecognitionException, TokenStreamException
        {
            iCalendar iCal = (iCalendar)Activator.CreateInstance(iCalendarType);;


            try {          // for error handling
                {          // ( ... )*
                    for (;;)
                    {
                        if ((LA(1) == BEGIN))
                        {
                            match(BEGIN);
                            match(COLON);
                            match(VCALENDAR);
                            match(CRLF);
                            icalbody(iCal);
                            match(END);
                            match(COLON);
                            match(VCALENDAR);
                            match(CRLF);
                        }
                        else
                        {
                            goto _loop3_breakloop;
                        }
                    }
                    _loop3_breakloop :;
                }            // ( ... )*
                iCal.OnLoad(EventArgs.Empty);
            }
            catch (RecognitionException ex)
            {
                reportError(ex);
                recover(ex, tokenSet_0_);
            }
            return(iCal);
        }
        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));
        }
Exemple #47
0
        /// <summary>
        /// Merges the current <see cref="iCalendar"/> with another iCalendar.
        /// <note>
        ///     Since each object is associated with one and only one iCalendar object,
        ///     the <paramref name="iCal"/> that is passed is automatically Disposed
        ///     in the process, because all of its objects are re-assocated with the new iCalendar.
        /// </note>
        /// </summary>
        /// <param name="iCal">The iCalendar to merge with the current <see cref="iCalendar"/></param>
        public void MergeWith(iCalendar iCal)
        {
            if (iCal != null)
            {
                // Merge all unique components
                foreach (UniqueComponent uc in iCal.UniqueComponents)
                {
                    this.AddChild(uc);
                }

                // Add all time zones
                foreach (DDay.iCal.Components.TimeZone tz in iCal.TimeZones)
                {
                    // Only add the time zone if it doesn't already exist
                    if (this.GetTimeZone(tz.TZID) == null)
                    {
                        this.AddChild(tz);
                    }
                }

                // Dispose of the calendar, since we just siphoned the components from it.
                iCal.Dispose();
            }
        }
Exemple #48
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"));
        }
Exemple #49
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");
            }
        }
Exemple #50
0
        /// <summary>
        /// Writes the showscases ical.
        /// </summary>
        private static void WriteShowscasesIcal()
        {
            string tzid = iCalTimeZone.FromLocalTimeZone().TZID;

            // Write out a calendar of each showcase.
            iCalendar showcasesCalendar = new iCalendar();
            showcasesCalendar.AddLocalTimeZone();

            foreach (Showcase showcase in _showcases.Where(s => s.Performances.Count > 0))
            {
                Event entry = showcasesCalendar.Create<Event>();
                entry.DTStamp = new iCalDateTime(showcase.Doors);
                entry.UID = GetMD5Hash(string.Format("{0}{1}", showcase.Doors.Ticks.ToString(), showcase.Name));
                entry.Start = new iCalDateTime(showcase.Doors, tzid);
                entry.End = new iCalDateTime(showcase.Performances.OrderBy(p => p.EndTime).Last().EndTime, tzid);
                entry.IsAllDay = false;
                entry.Location = showcase.Venue;
                entry.Summary = showcase.Name;

                foreach (Performance performance in showcase.Performances)
                {
                    entry.Description += string.Format(
                        "{0} ({1}): {2} - {3}\n",
                        performance.Artist.Name,
                        performance.PerformanceType,
                        performance.StartTime.ToString("h:mm tt"),
                        performance.EndTime.ToString("h:mm tt"));
                }

                entry.Description += string.Format(
                    "\n{0}\n{1}\n\nTickets\n{2}\n\nAll Ages? {3}\nIncluded in pass? {4}{5}",
                    showcase.Name,
                    showcase.ShowcaseLink,
                    showcase.TicketLink,
                    showcase.IsAllAges ? "yes" : "no",
                    showcase.IsIncludedWithPass ? "yes" : "no",
                    showcase.SetTimesAreEstimated ? "\n\nWarning: Set times are estimated for this showcase and are almost certainly incorrect." : string.Empty);
            }

            new iCalendarSerializer().Serialize(showcasesCalendar, Path.Combine(_dataDirectory, "showcases.ics"));
        }
Exemple #51
0
        /// <summary>
        /// Write out data in iCal format for consumption by calendar apps.
        /// </summary>
        private static void WritePerformancesIcal()
        {
            string tzid = iCalTimeZone.FromLocalTimeZone().TZID;

            // Write out a calendar of each individual performance.
            iCalendar performancesCalendar = new iCalendar();
            performancesCalendar.AddLocalTimeZone();

            foreach (Performance performance in _performances)
            {
                Event entry = performancesCalendar.Create<Event>();
                entry.DTStamp = new iCalDateTime(performance.StartTime);
                entry.UID = GetMD5Hash(string.Format("{0}{1}{2}", performance.StartTime.Ticks.ToString(), performance.Showcase.Name, performance.Artist.Name));
                entry.Start = new iCalDateTime(performance.StartTime, tzid);
                entry.End = new iCalDateTime(performance.EndTime, tzid);
                entry.IsAllDay = false;
                entry.Location = performance.Showcase.Venue;
                entry.Summary = performance.Artist.Name;
                entry.Description = string.Format(
                    "{0} ({1})\n{2}\n\n{3}\n{4}\n\nTickets\n{5}\n\nAll Ages? {6}\nIncluded in pass? {7}{8}",
                    performance.Artist.Name,
                    performance.PerformanceType,
                    performance.Artist.ArtistLink,
                    performance.Showcase.Name,
                    performance.Showcase.ShowcaseLink,
                    performance.Showcase.TicketLink,
                    performance.Showcase.IsAllAges ? "yes" : "no",
                    performance.Showcase.IsIncludedWithPass ? "yes" : "no",
                    performance.Showcase.SetTimesAreEstimated ? "\n\nWarning: Set times are estimated for this showcase and are almost certainly incorrect." : string.Empty);
            }

            new iCalendarSerializer().Serialize(performancesCalendar, Path.Combine(_dataDirectory, "performances.ics"));
        }
Exemple #52
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 );
        }
Exemple #53
0
        //public ArrayList GetTodos(string category)
        //{
        //    ArrayList t = new ArrayList();
        //    foreach (Todo todo in Todos)
        //    {
        //        if (todo.Categories != null)
        //        {
        //            foreach (TextCollection cat in todo.Categories)
        //            {
        //                foreach (Text text in cat.Values)
        //                {
        //                    if (text.Value == category)
        //                        t.Add(todo);
        //                }
        //            }
        //        }
        //    }

        //    return t;
        //}

        /// <summary>
        /// Merges the current <see cref="iCalendar"/> with another iCalendar.
        /// <note>
        ///     Since each object is associated with one and only one iCalendar object,
        ///     the <paramref name="iCal"/> that is passed is automatically Disposed
        ///     in the process, because all of its objects are re-assocated with the new iCalendar.
        /// </note>
        /// </summary>
        /// <param name="iCal">The iCalendar to merge with the current <see cref="iCalendar"/></param>
        public void MergeWith(iCalendar iCal)
        {
            if (iCal != null)
            {
                foreach (UniqueComponent uc in iCal.UniqueComponents)
                    this.AddChild(uc);
                iCal.Dispose();
            }
        }