Inheritance: CalendarComponent, IAlarm
Exemple #1
0
        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;
                // В ячейке "Соперник" нужно удалить символ неразрывного пробела ("&nbsp")
                match.Rival = cells[5].InnerText.Replace("&nbsp;", "");
                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;
        }
        public bool SendMail()
        {
            try
            {
                var sc = new SmtpClient("smtp.gmail.com")
                    {
                        Port = 587,
                        Credentials = new System.Net.NetworkCredential("username", "password"),
                        EnableSsl = true
                    };

                var msg = new MailMessage {From = new MailAddress("*****@*****.**", "System")};
                foreach (MailAddressObject obj in Mail)
                {
                    msg.To.Add(new MailAddress(obj.Email, obj.Name));
                }
                msg.Subject = Subject;
                msg.Body = Body;

                var iCal = new iCalendar {Method = "REQUEST"};

                // Create the event
                var evt = iCal.Create<Event>();

                evt.Summary = Summary;
                evt.Start = new iCalDateTime(StartTime.Year, StartTime.Month, StartTime.Day, StartTime.Hour, StartTime.Minute, StartTime.Second);
                evt.End = new iCalDateTime(EndTime.Year, EndTime.Month, EndTime.Day, EndTime.Hour, EndTime.Minute, EndTime.Second);
                evt.Description = Description;
                evt.Location = Location;

                //evt.Organizer = new Organizer("Phats");
                var alarm = new Alarm
                    {
                        Action = AlarmAction.Display,
                        Summary = AlarmSummary,
                        Trigger =
                            new Trigger(TimeSpan.FromMinutes(0 - ServiceFacade.SettingsHelper.TimeLeftRemindAppointment))
                    };
                evt.Alarms.Add(alarm);

                var serializer = new iCalendarSerializer(iCal);
                string icalData = serializer.SerializeToString(serializer);

                // Set up the different mime types contained in the message
                var loTextType = new System.Net.Mime.ContentType("text/plain");
                var loHtmlType = new System.Net.Mime.ContentType("text/html");
                var loCalendarType = new System.Net.Mime.ContentType("text/calendar");

                // Add parameters to the calendar header
                if (loCalendarType.Parameters != null)
                {
                    loCalendarType.Parameters.Add("method", "REQUEST");
                    loCalendarType.Parameters.Add("name", "meeting.ics");
                }

                AlternateView loTextView = AlternateView.CreateAlternateViewFromString(icalData, loTextType);
                msg.AlternateViews.Add(loTextView);

                AlternateView loHtmlView = AlternateView.CreateAlternateViewFromString(icalData, loHtmlType);
                msg.AlternateViews.Add(loHtmlView);

                AlternateView loCalendarView = AlternateView.CreateAlternateViewFromString(icalData, loCalendarType);
                loCalendarView.TransferEncoding = System.Net.Mime.TransferEncoding.SevenBit;
                msg.AlternateViews.Add(loCalendarView);

                sc.Send(msg);
                return true;
            }
            catch (Exception ex)
            {
                //SingletonLogger.Instance.Error("MailAppointment.SendMail", ex);
                return false;
            }
        }
        /// <summary>
        /// This method is used when Start and End time both are supplied
        /// </summary>
        /// <param name="title"></param>
        /// <param name="body"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <param name="location"></param>
        /// <param name="organizer"></param>
        /// <param name="eventId"></param>
        /// <param name="allDayEvent"></param>
        /// <returns></returns>
        private static string CreateCalendarEvent(string title, string body, DateTime startDate, DateTime endDate, string location, string organizer, string eventId, bool allDayEvent)
        {
            var iCal = new iCalendar
            {
                Method = "PUBLISH", //PUBLISH
                Version = "2.0"
            };
            // Create the event
            var evt = iCal.Create<Event>();
            //Subject
            evt.Summary = title;
            //Start Time
            evt.Start = new iCalDateTime(startDate.Year,
                                         startDate.Month, startDate.Day, startDate.Hour,
                                         startDate.Minute, startDate.Second);
            //End Time
            evt.End = new iCalDateTime(endDate.Year,
                                         endDate.Month, endDate.Day, endDate.Hour,
                                         endDate.Minute, endDate.Second);
            //Description of the Event
            evt.Description = body;
            //Location for the Event
            evt.Location = location;
            //Is All Day flag
            evt.IsAllDay = allDayEvent;
            //Event Id
            evt.UID = new Guid().ToString();

            //organizer is mandatory for outlook 2007 - think about
            // throwing an exception here.
            if (!String.IsNullOrEmpty(organizer))
            {
                evt.Organizer = new Organizer(organizer);
            }
            else
            {
                throw new Exception("Organizer provided was null");
            }

            if (!String.IsNullOrEmpty(eventId))
            {
                evt.UID = eventId;
            }

            var alarm = new Alarm
            {
                Duration = new TimeSpan(0, 15, 0),
                Trigger = new Trigger(new TimeSpan(0, 15, 0)),
                Action = AlarmAction.Display,
                Description = "Reminder"
            };

            evt.Alarms.Add(alarm);

            // Save into calendar file.
            var serializer = new iCalendarSerializer(iCal);

            return serializer.SerializeToString(iCal);
        }
        private static string CreateCalendarEvent(string title, string body, DateTime startDate, double duration, string location, string organizer, string eventId, bool allDayEvent, int recurrenceDaysInterval, int recurrenceCount, string freqType)
        {
            var iCal = new iCalendar
            {
                Method = "PUBLISH", //PUBLISH
                Version = "2.0"
            };

            //if i use method PUBLISH:
            //if i use method REQUEST: it's an appointment, but then says meeting cannot be found in the calendar. if you click no response required, it gets deleted

            // outlook 2003 needs this property,
            //  or we'll get an error (a Lunar error!)

            // Create the event
            var evt = iCal.Create<Event>();
            evt.Summary = title;
            evt.Start = new iCalDateTime(startDate.Year,
                                         startDate.Month, startDate.Day, startDate.Hour,
                                         startDate.Minute, startDate.Second);
            evt.Duration = TimeSpan.FromHours(duration);
            evt.Description = body;
            evt.Location = location;

            evt.IsAllDay = allDayEvent;

            evt.UID = new Guid().ToString();

            if (recurrenceDaysInterval > 0)
            {
                RecurrencePattern rp = new RecurrencePattern();
                if (freqType == "Daily")
                {
                    rp.Frequency = FrequencyType.Daily;
                }
                else if (freqType == "Weekly")
                {
                    rp.Frequency = FrequencyType.Weekly;
                }
                else if (freqType == "Yearly")
                {
                    rp.Frequency = FrequencyType.Yearly;
                }
                else if (freqType == "Monthly")
                {
                    rp.Frequency = FrequencyType.Monthly;
                }
                rp.Interval = recurrenceDaysInterval; // interval of days
                rp.Count = recurrenceCount; // number of recurrence count
                evt.RecurrenceRules.Add(rp);
            }

            //organizer is mandatory for outlook 2007 - think about
            // throwing an exception here.
            if (!String.IsNullOrEmpty(organizer))
            {
                evt.Organizer = new Organizer(organizer);
            }
            else
            {
                throw new Exception("Organizer provided was null");
            }

            if (!String.IsNullOrEmpty(eventId))
            {
                evt.UID = eventId;
            }

            //"REQUEST" will update an existing event with the same
            // UID (Unique ID) and a newer time stamp.
            //if (updatePreviousEvent)
            //{
            //    iCal.Method = "REQUEST";
            //}

            var alarm = new Alarm
            {
                Duration = new TimeSpan(0, 15, 0),
                Trigger = new Trigger(new TimeSpan(0, 15, 0)),
                Action = AlarmAction.Display,
                Description = "Reminder"
            };

            evt.Alarms.Add(alarm);

            // Save into calendar file.
            var serializer = new iCalendarSerializer(iCal);

            return serializer.SerializeToString(iCal);
        }
Exemple #6
0
        /// <summary>
        /// Creates a calendar with 2 events, and returns it.
        /// </summary>
        static IICalendar CreateCalendar()
        {
            // First load a file containing time zone information for North & South America
            IICalendar timeZones = iCalendar.LoadFromFile("America.ics")[0];

            // Add the time zones we are going to use to our calendar
            // If we're not sure what we'll use, we could simply copy the
            // entire time zone information instead:
            //
            // IICalendar iCal = timeZones.Copy<IICalendar>();
            //
            // This will take significantly more disk space, and can slow
            // down performance, so I recommend you determine which time
            // zones will be used and only copy the necessary zones.
            IICalendar iCal = new iCalendar();
            iCal.AddChild(timeZones.GetTimeZone("America/New_York"));
            iCal.AddChild(timeZones.GetTimeZone("America/Denver"));

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

            // Set the one-line summary of the event
            evt.Summary = "The first Monday and second-to-last Monday of each month";

            // Set the longer description of the event
            evt.Description = "A more in-depth description of this event.";

            // Set the event to start at 11:00 A.M. New York time on January 2, 2007.
            evt.Start = new iCalDateTime(2007, 1, 2, 11, 0, 0, "America/New_York", iCal);

            // Set the duration of the event to 1 hour.
            // NOTE: this will automatically set the End time of the event
            evt.Duration = TimeSpan.FromHours(1);

            // The event has been confirmed
            evt.Status = EventStatus.Confirmed;

            // Set the geographic location (latitude,longitude) of the event
            evt.GeographicLocation = new GeographicLocation(114.2938, 32.982);

            evt.Location = "Home office";
            evt.Priority = 7;

            // Add an organizer to the event.
            // This is the person who created the event (or who is in charge of it)
            evt.Organizer = new Organizer("MAILTO:[email protected]");
            // Indicate that this organizer is a member of another group
            evt.Organizer.Parameters.Add("MEMBER", "MAILTO:[email protected]");

            // Add a person who will attend the event
            // FIXME: re-implement this
            //evt.Attendees.Add(new Attendee("*****@*****.**"));

            // Add categories to the event
            evt.Categories.Add("Work");
            evt.Categories.Add("Personal");

            // Add some comments to the event
            evt.Comments.Add("Comment #1");
            evt.Comments.Add("Comment #2");

            // Add resources that will be used for the event
            evt.Resources.Add("Conference Room #2");
            evt.Resources.Add("Projector #4");

            // Add contact information to this event, with an optional link to further information
            // FIXME: reimplement this:
            //evt.Contacts.Add("Doug Day (XXX) XXX-XXXX", new Uri("http://www.someuri.com/pdi/dougd.vcf"));

            // Set the identifier for the event.  NOTE: this will happen automatically
            // if you don't do it manually.  We set it manually here so we can easily
            // refer to this event later.
            evt.UID = "1234567890";

            // Now, let's add a recurrence pattern to this event.
            // It needs to happen on the first Monday and
            // second to last Monday of each month.
            RecurrencePattern rp = new RecurrencePattern();
            rp.Frequency = FrequencyType.Monthly;
            rp.ByDay.Add(new WeekDay(DayOfWeek.Monday, FrequencyOccurrence.First));
            rp.ByDay.Add(new WeekDay(DayOfWeek.Monday, FrequencyOccurrence.SecondToLast));
            evt.RecurrenceRules.Add(rp);

            // Let's also add an alarm on this event so we can be reminded of it later.
            Alarm alarm = new Alarm();

            // Display the alarm somewhere on the screen.
            alarm.Action = AlarmAction.Display;

            // This is the text that will be displayed for the alarm.
            alarm.Summary = "Alarm for the first Monday and second-to-last Monday of each month";

            // The alarm is set to occur 30 minutes before the event
            alarm.Trigger = new Trigger(TimeSpan.FromMinutes(-30));

            // Set the alarm to repeat twice (for a total of 3 alarms)
            // before the event.  Each repetition will occur 10 minutes
            // after the initial alarm.  In english - that means
            // the alarm will go off 30 minutes before the event,
            // then again 20 minutes before the event, and again
            // 10 minutes before the event.
            alarm.Repeat = 2;
            alarm.Duration = TimeSpan.FromMinutes(10);

            // Add the alarm to the event
            evt.Alarms.Add(alarm);

            // Create another (much more simple) event
            evt = iCal.Create<Event>();
            evt.Summary = "Every month on the 21st";
            evt.Description = "A more in-depth description of this event.";
            evt.Start = new iCalDateTime(2007, 1, 21, 16, 0, 0, "America/New_York", iCal);
            evt.Duration = TimeSpan.FromHours(1.5);

            rp = new RecurrencePattern();
            rp.Frequency = FrequencyType.Monthly;
            evt.RecurrenceRules.Add(rp);

            return iCal;
        }