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 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)); }
/// <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")); }
/// <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")); }
public static void Main(string[] args) { // Название нашей таблицы с расписанием. string filePath = @"test2.xlsx"; // Парсим xlsx-таблицу List<WorkDay> week = ParseExcelSchedule.Parse(filePath); // Задаем дату начала семестра. iCalDateTime startStudy = new iCalDateTime(2015, 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)); // В каждом занятии пробегаемся по неделям, когда оно повторяется. foreach (int number in workDay.repeatAt) { // Плюсуем к временной дате (номер недели - 1, т.к. чтобы перейти // к первой неделе не нужно плюсовать неделю) * 7 дней) и // приводим к локальной временной зоне. iCalDateTime StartClass = new iCalDateTime(tmpDate.AddDays((number - 1) * 7).Local); // Если неделя первая (подразумевается, что она не полная) // и день занятий раньше для начала учебы, тогда не записываем его. if ((number == 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; newClass.DTStart = newClass.DTStart.Add(workDay.timeClassStart); newClass.Duration = workDay.timeClassEnd - workDay.timeClassStart; 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; // Добавим напоминание к парам, чтобы не забыть о них. 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, "Расписание.ics"); Console.WriteLine("Календарь расписания сохранён успешно" + Environment.NewLine); }
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; }