public void SERIALIZE32() { iCalendar iCal = new iCalendar(); iCal.AddProperty("X-WR-CALNAME", "DDay Test"); iCal.AddProperty("X-WR-CALDESC", "Events for a DDay Test"); iCal.AddProperty("X-PUBLISHED-TTL", "PT30M"); iCal.ProductID = "-//DDAYTEST//NONSGML www.test.com//EN"; // Create an event in the iCalendar Event evt = iCal.Create <Event>(); //Populate the properties evt.Start = new iCalDateTime(2009, 6, 28, 8, 0, 0); evt.Duration = TimeSpan.FromHours(1); evt.Url = new URI("http://www.ftb.pl/news/59941_0_1/tunnel-electrocity-2008-timetable.htm"); evt.Summary = "This is a title"; evt.Description = "This is a description"; iCalendarSerializer serializer = new iCalendarSerializer(iCal); string output = serializer.SerializeToString(); serializer.Serialize(@"Calendars\Serialization\SERIALIZE32.ics"); Assert.IsFalse(Regex.IsMatch(output, @"\r\n[\r\n]")); SerializeTest("SERIALIZE32.ics", typeof(iCalendarSerializer)); }
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(); }
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)); }
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)); }
public void XProperty4() { iCalendar iCal = new iCalendar(); iCal.AddProperty("X-WR-CALNAME", "DDay Test"); iCal.AddProperty("X-WR-CALDESC", "Events for a DDay Test"); iCal.AddProperty("X-PUBLISHED-TTL", "PT30M"); iCal.ProductID = "-//DDAYTEST//NONSGML www.test.com//EN"; // Create an event in the iCalendar Event evt = iCal.Create<Event>(); // Populate the properties evt.Start = new iCalDateTime(2009, 6, 28, 8, 0, 0); evt.Duration = TimeSpan.FromHours(1); evt.Url = new Uri("http://www.ftb.pl/news/59941_0_1/tunnel-electrocity-2008-timetable.htm"); evt.Summary = "This is a title"; evt.Description = "This is a description"; iCalendarSerializer serializer = new iCalendarSerializer(); string output = serializer.SerializeToString(iCal); serializer.Serialize(iCal, @"Calendars/Serialization/XProperty4.ics"); Assert.IsFalse(Regex.IsMatch(output, @"\r\n[\r\n]")); SerializeTest("XProperty4.ics", typeof(iCalendarSerializer)); }
public static void Main(string[] args) { // Название нашей таблицы с расписанием. string filePath = filename + @".xlsx"; // Парсим xlsx-таблицу List <WorkDay> week = ParseExcelSchedule.Parse(filePath); // Задаем дату начала семестра. iCalDateTime startStudy = new iCalDateTime(2016, 9, 1); // Создаём календарь, в который будем сохранять матчи. iCalendar CalForSchedule = new iCalendar { Method = "PUBLISH", Version = "2.0", }; // Эти настройки нужны для календаря Mac, чтобы он был неотличим от // оригинального календаря (т.е. созданного внутри Mac Calendar) CalForSchedule.AddProperty("CALSCALE", "GREGORIAN"); CalForSchedule.AddProperty("X-WR-CALNAME", "Расписание"); CalForSchedule.AddProperty("X-WR-TIMEZONE", "Europe/Moscow"); CalForSchedule.AddLocalTimeZone(); // Сохраняем дату начала первой учебной недели. //TODO тут какое-то говно с преобразованием iCalDateTime в IDateTime int numberOfFirstDayOfFirstStudyWeek = startStudy.DayOfYear - ParseExcelSchedule.GetIntNumberFromDayWeek(startStudy.DayOfWeek.ToString()); iCalDateTime firstDayOfFirstStudyWeek = new iCalDateTime(startStudy.FirstDayOfYear.AddDays(numberOfFirstDayOfFirstStudyWeek)); // Пробегаемся по всем учебным дням в неделе. foreach (WorkDay workDay in week) { // Информация для отладки. Console.WriteLine(workDay); // Плюсуем к понедельнику первой учебной недели номер нашего обрабатываемого дня iCalDateTime tmpDate = new iCalDateTime(firstDayOfFirstStudyWeek.AddDays(workDay.dayNumber - 1)); // Плюсуем к временной дате (номер недели - 1, т.к. чтобы перейти // к первой неделе не нужно плюсовать неделю) * 7 дней) и // приводим к локальной временной зоне. // // FIXME // Для второго семестра приходится минусовать 24 недели //iCalDateTime StartClass = new iCalDateTime(tmpDate.AddDays((number - 1 - 23) * 7).Local); iCalDateTime StartClass = new iCalDateTime(tmpDate.AddDays((workDay.repeatAt[0] - 1) * 7).Local); // Если неделя первая (подразумевается, что она не полная) // и день занятий раньше для начала учебы, тогда не записываем его. //if ((1 == 1 // && StartClass.LessThan(startStudy)) // || // (StartClass.GreaterThanOrEqual(new iCalDateTime(startStudy.FirstDayOfYear.AddDays(363))) // && !(isLeapYear(StartClass.Year))) // || // (StartClass.GreaterThanOrEqual(new iCalDateTime(startStudy.FirstDayOfYear.AddDays(364))) // && isLeapYear(StartClass.Year))) // continue; Event newClass = CalForSchedule.Create <Event>(); newClass.DTStart = StartClass; // OLD: StartClass newClass.DTStart = newClass.DTStart.Add(workDay.timeClassStart); newClass.Duration = workDay.timeClassEnd - workDay.timeClassStart; if (workDay.typeClass == "Семинар") { newClass.Summary = Emojione.Emojione.ShortnameToUnicode(":closed_book:"); } else { newClass.Summary = Emojione.Emojione.ShortnameToUnicode(":green_book:"); } newClass.Summary += string.Format("{0}", workDay.nameSubject); newClass.Description = string.Format("Преподаватель: {0}", workDay.nameLecturer); newClass.Location = string.Format("{0}, {1}", workDay.typeClass, workDay.place); newClass.IsAllDay = false; RecurrencePattern rp = new RecurrencePattern("RRULE:FREQ=WEEKLY;INTERVAL=1;COUNT=" + (workDay.repeatAt.Max() - workDay.repeatAt.Min() + 1)); newClass.RecurrenceRules.Add(rp); //event.RecurrenceRules.Add(rp); //newClass.AddProperty("RRULE", @"FREQ = WEEKLY; INTERVAL = 1; COUNT = " + (); // Добавим напоминание к парам, чтобы не забыть о них. Alarm alarm = new Alarm(); alarm.Trigger = new Trigger(TimeSpan.FromMinutes(-5)); alarm.Description = "Напоминание о событии"; alarm.AddProperty("ACTION", "DISPLAY"); newClass.Alarms.Add(alarm); // Если это первая пара за день, напоминаем о ней за 2,5 часа. //if (workDay.isFirstClassesOfADay) //{ // Alarm alarm2 = new Alarm(); // alarm2.Trigger = new Trigger(TimeSpan.FromMinutes(-150)); // alarm2.Description = "Напоминание о событии"; // alarm2.AddProperty("ACTION", "DISPLAY"); // newClass.Alarms.Add(alarm2); //} } // Сериализуем наш календарь. iCalendarSerializer serializer = new iCalendarSerializer(); serializer.Serialize(CalForSchedule, fileCalcName + @".ics"); Console.WriteLine("Календарь расписания сохранён успешно" + Environment.NewLine); }
/// <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); }
public static void Main(string[] args) { // Адрес сайта, откуда будем парсить данные. string WebAddress = @"http://www.sports.ru/barcelona/calendar/"; // Создаём экземляры классов веб-страницы и веб-документа HtmlWeb WebGet = new HtmlWeb(); // Загружаем html-документ с указанного сайта. HtmlDocument htmlDoc = WebGet.Load(WebAddress); // Сюда будем сохранять матчи Matches MatchesFC = new Matches(); // Парсим название клуба (удаляя символ возрата каретки) MatchesFC.NameFC = htmlDoc.DocumentNode. SelectSingleNode(".//*[@class='titleH1']"). FirstChild.InnerText.Replace("\r\n", ""); // Находим в этом документе таблицу с датами матчей с помощью XPath-выражений. HtmlNode Table = htmlDoc.DocumentNode.SelectSingleNode(".//*[@class='stat-table']/tbody"); // Из полученной таблицы выделяем все элементы-строки с тегом "tr". IEnumerable <HtmlNode> rows = Table.Descendants().Where(x => x.Name == "tr"); foreach (var row in rows) { // Создаём коллекцию из ячеек каждой строки. HtmlNodeCollection cells = row.ChildNodes; // Создаём экземпляр класса SingleMatch, чтобы затем добавить его в лист. SingleMatch match = new SingleMatch(); // Парсим дату, предварительно убирая из строки символ черточки "|", // иначе наш метод TryParse не сможет правильно обработать. DateTime time; DateTime.TryParse(cells[1].InnerText.Replace("|", " "), out time); match.StartTime = time; // Остальные поля просто заполняем, зная нужный нам индекс. match.Tournament = cells[3].InnerText; // В ячейке "Соперник" нужно удалить символ неразрывного пробела (" ") match.Rival = cells[5].InnerText.Replace(" ", ""); match.Place = cells[6].InnerText; // Добавляем одиночный матч в лист матчей. MatchesFC.ListMatches.Add(match); } // Создаём календарь, в который будем сохранять матчи. iCalendar CalForMatches = new iCalendar { Method = "PUBLISH", Version = "2.0" }; // Эти настройки нужны для календаря Mac, чтобы он был неотличим от // оригинального календаря (т.е. созданного внутри Mac Calendar) CalForMatches.AddProperty("CALSCALE", "GREGORIAN"); CalForMatches.AddProperty("X-WR-CALNAME", "Mатчи ФК " + MatchesFC.NameFC); CalForMatches.AddProperty("X-WR-TIMEZONE", "Europe/Moscow"); CalForMatches.AddLocalTimeZone(); // Сохраняем полученный результат. foreach (SingleMatch match in MatchesFC.ListMatches) { Event newMatch = CalForMatches.Create <Event>(); newMatch.DTStart = new iCalDateTime(match.StartTime); newMatch.Duration = new TimeSpan(2, 30, 0); newMatch.Summary = string.Format("{0} : {1}", MatchesFC.NameFC, match.Rival); newMatch.Description = string.Format("{0}. {1} : {2}, {3}", match.Tournament, MatchesFC.NameFC, match.Rival, match.Place); // Добавим напоминание к матчам, чтобы не забыть о них Alarm alarm = new Alarm(); alarm.Trigger = new Trigger(TimeSpan.FromMinutes(-10)); alarm.Description = "Напоминание о событии"; alarm.AddProperty("ACTION", "DISPLAY"); newMatch.Alarms.Add(alarm); } // Сериализуем наш календарь. iCalendarSerializer serializer = new iCalendarSerializer(); serializer.Serialize(CalForMatches, MatchesFC.NameFC + ".ics"); Console.WriteLine("Календарь матчей сохранён успешно" + Environment.NewLine); return; }