Inheritance: EncodableDataType, IDateTime
コード例 #1
0
        public List <Period> Evaluate(iCalDateTime StartDate, iCalDateTime FromDate, iCalDateTime EndDate)
        {
            List <Period> periods = new List <Period>();

            if (StartDate > FromDate)
            {
                FromDate = StartDate;
            }

            if (EndDate < FromDate ||
                FromDate > EndDate)
            {
                return(periods);
            }

            foreach (Period p in Periods)
            {
                if (!periods.Contains(p))
                {
                    periods.Add(p);
                }
            }

            return(periods);
        }
コード例 #2
0
        protected IDateTime ConvertToIDateTime(DateTime dt, IDateTime referenceDate)
        {
            IDateTime newDt = new iCalDateTime(dt, referenceDate.TZID);

            newDt.AssociateWith(referenceDate);
            return(newDt);
        }
コード例 #3
0
 /// <summary>
 /// Evaluates component recurrences for the given range of time, for
 /// the type of recurring component specified.
 /// </summary>
 /// <typeparam name="T">The type of component to be evaluated for recurrences.</typeparam>
 /// <param name="FromDate">The beginning date/time of the range to test.</param>
 /// <param name="ToDate">The end date/time of the range to test.</param>
 public void Evaluate <T>(iCalDateTime FromDate, iCalDateTime ToDate)
 {
     foreach (iCalendar iCal in _Calendars)
     {
         iCal.Evaluate <T>(FromDate, ToDate);
     }
 }
コード例 #4
0
        public override IList <IPeriod> Evaluate(IDateTime referenceDate, DateTime periodStart, DateTime periodEnd, bool includeReferenceDateInResults)
        {
            // Create a recurrence pattern suitable for use during evaluation.
            IRecurrencePattern pattern = ProcessRecurrencePattern(referenceDate);

            // Enforce evaluation restrictions on the pattern.
            EnforceEvaluationRestrictions(pattern);

            Periods.Clear();
            foreach (DateTime dt in GetDates(referenceDate, periodStart, periodEnd, -1, pattern, includeReferenceDateInResults))
            {
                // Turn each resulting date/time into an IDateTime and associate it
                // with the reference date.
                IDateTime newDt = new iCalDateTime(dt, referenceDate.TZID);

                // NOTE: fixes bug #2938007 - hasTime missing
                newDt.HasTime = referenceDate.HasTime;

                newDt.AssociateWith(referenceDate);

                // Create a period from the new date/time.
                IPeriod p = new Period(newDt);

                if (!Periods.Contains(p))
                {
                    Periods.Add(p);
                }
            }

            return(Periods);
        }
コード例 #5
0
        virtual public TimeZoneObservance?GetObservance(IDateTime dt)
        {
            if (Parent == null)
            {
                throw new Exception("Cannot call GetObservance() on a TimeZoneInfo whose Parent property is null.");
            }

            // Normalize date/time values within this time zone to a UTC value.
            DateTime normalizedDt = dt.Value;

            if (string.Equals(dt.TZID, TZID))
            {
                dt           = new iCalDateTime(OffsetTo.ToUTC(dt.Value));
                normalizedDt = OffsetTo.ToUTC(normalizedDt);
            }

            // Let's evaluate our time zone observances to find the
            // observance that applies to this date/time value.
            IEvaluator parentEval = Parent.GetService(typeof(IEvaluator)) as IEvaluator;

            if (parentEval != null)
            {
                // Evaluate the date/time in question.
                parentEval.Evaluate(Start, DateUtil.GetSimpleDateTimeData(Start), normalizedDt, true);
                foreach (IPeriod period in m_Evaluator.Periods)
                {
                    if (period.Contains(dt))
                    {
                        return(new TimeZoneObservance(period, this));
                    }
                }
            }
            return(null);
        }
コード例 #6
0
        private void EnsureProperties()
        {
            if (string.IsNullOrEmpty(UID))
            {
                // Create a new UID for the component
                UID = new UIDFactory().Build();
            }

            if (!Properties.ContainsKey("SEQUENCE"))
            {
                Sequence = 0;
            }

            if (Created == null)
            {
                // Here, we don't simply set to DateTime.Now because DateTime.Now contains milliseconds, and
                // the iCalendar standard doesn't care at all about milliseconds.  Therefore, when comparing
                // two calendars, one generated, and one loaded from file, they may be functionally identical,
                // but be determined to be different due to millisecond differences.
                DateTime now = DateTime.Now;
                Created = new iCalDateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);
            }

            if (DTStamp == null)
            {
                DTStamp = Created.Copy <IDateTime>();
            }
        }
コード例 #7
0
ファイル: iCalDateTime.cs プロジェクト: zumka/DDay.iCal
        public void AssociateWith(IDateTime dt)
        {
            if (AssociatedObject == null && dt.AssociatedObject != null)
            {
                AssociatedObject = dt.AssociatedObject;
            }
            else if (AssociatedObject != null && dt.AssociatedObject == null)
            {
                dt.AssociatedObject = AssociatedObject;
            }

            // If these share the same TZID, then let's see if we
            // can share the time zone observance also!
            if (TZID != null && string.Equals(TZID, dt.TZID))
            {
                if (TimeZoneObservance != null && dt.TimeZoneObservance == null)
                {
                    IDateTime normalizedDt = new iCalDateTime(TimeZoneObservance.Value.TimeZoneInfo.OffsetTo.ToUTC(dt.Value));
                    if (TimeZoneObservance.Value.Contains(normalizedDt))
                    {
                        dt.TimeZoneObservance = TimeZoneObservance;
                    }
                }
                else if (dt.TimeZoneObservance != null && TimeZoneObservance == null)
                {
                    IDateTime normalizedDt = new iCalDateTime(dt.TimeZoneObservance.Value.TimeZoneInfo.OffsetTo.ToUTC(Value));
                    if (dt.TimeZoneObservance.Value.Contains(normalizedDt))
                    {
                        TimeZoneObservance = dt.TimeZoneObservance;
                    }
                }
            }
        }
コード例 #8
0
        private void EnsureProperties()
        {
            if (string.IsNullOrEmpty(UID))
            {
                // Create a new UID for the component
                UID = new UIDFactory().Build();
            }

            if (!Properties.ContainsKey("SEQUENCE"))
            {
                Sequence = 0;
            }

            // NOTE: removed setting the 'CREATED' property here since it breaks serialization.
            // See https://sourceforge.net/projects/dday-ical/forums/forum/656447/topic/3754354
            if (DTStamp == null)
            {
                // Here, we don't simply set to DateTime.Now because DateTime.Now contains milliseconds, and
                // the iCalendar standard doesn't care at all about milliseconds.  Therefore, when comparing
                // two calendars, one generated, and one loaded from file, they may be functionally identical,
                // but be determined to be different due to millisecond differences.
                DateTime now = DateTime.Now;
                DTStamp = new iCalDateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);
            }
        }
コード例 #9
0
 /// <summary>
 /// Evaluates component recurrences for the given range of time, for
 /// the type of recurring component specified.
 /// </summary>
 /// <typeparam name="T">The type of component to be evaluated for recurrences.</typeparam>
 /// <param name="FromDate">The beginning date/time of the range to test.</param>
 /// <param name="ToDate">The end date/time of the range to test.</param>
 public void Evaluate <T>(iCalDateTime FromDate, iCalDateTime ToDate)
 {
     foreach (RecurringComponent rc in RecurringComponents)
     {
         if (rc is T)
         {
             rc.Evaluate(FromDate, ToDate);
         }
     }
 }
コード例 #10
0
        /// <summary>
        /// Returns all occurrences of components of type T that start within the date range provided.
        /// All components occurring between <paramref name="startTime"/> and <paramref name="endTime"/>
        /// will be returned.
        /// </summary>
        /// <param name="startTime">The starting date range</param>
        /// <param name="endTime">The ending date range</param>
        virtual public List <Occurrence> GetOccurrences <T>(iCalDateTime startTime, iCalDateTime endTime) where T : RecurringComponent
        {
            List <Occurrence> occurrences = new List <Occurrence>();

            foreach (iCalendar iCal in _Calendars)
            {
                occurrences.AddRange(iCal.GetOccurrences <T>(startTime, endTime));
            }

            occurrences.Sort();
            return(occurrences);
        }
コード例 #11
0
        public void GenerateNotification()
        {
            try
            {
                List<EventViewModel> todaysEvents = new List<EventViewModel>();
                // GET all events
                var events = _eventService.GetEvents();
                // Loop thru each event and check if any events exists for today
                foreach (var eachEvent in events)
                {
                    // Send notification for each event
                    var evt = _ical.Create<DDay.iCal.Event>();
                    evt.Start = new iCalDateTime(Convert.ToDateTime(eachEvent.StartDate));
                    evt.End = new iCalDateTime(Convert.ToDateTime(eachEvent.EndDate));
                    IDateTime start = new iCalDateTime(System.DateTime.Today);
                    IDateTime end = new iCalDateTime(System.DateTime.Today.AddDays(1));
                    string rule = eachEvent.RecurrenceRule;
                    evt.RecurrenceRules.Add(new RecurrencePattern(rule));
                    foreach (var occurence in evt.GetOccurrences(start, end))
                    {
                        if (occurence.Period.StartTime.Value.Date == System.DateTime.Today && Convert.ToDateTime(occurence.Period.StartTime.Value.ToString()) <= Convert.ToDateTime(evt.End.ToString()))
                        {
                            ++_affectedEvents;
                            //todaysEvents.Add(eachEvent);
                            if ((ReminderType)Enum.Parse(typeof(ReminderType), eachEvent.ReminderMode.ToString().Replace(" ", "_")) == ReminderType.Email_Only)
                            {
                                _emailService.SendEmail(eachEvent);
                            }
                            else if ((ReminderType)Enum.Parse(typeof(ReminderType), eachEvent.ReminderMode.ToString().Replace(" ", "_")) == ReminderType.Mobile_Only)
                            {
                                _emailService.SendEmail(eachEvent);
                            }
                            else
                            {
                                _emailService.SendEmail(eachEvent);
                            }
                        }
                    }

                    // Create an audit record of the notification cycle
                    _auditService.UpdateAudit(new AuditViewModel() { Status = _affectedEvents > 0 ? "UP": "DOWN", Comments = string.Format("{0} events found and notified today.",_affectedEvents), Id = 1 });

                }
            }
            catch (Exception ex)
            {
                _emailService.SendEmail(new EmailViewModel() { Title= "Paytime notification couldn't be sent", Subject = "Paytime notification couldn't be sent", Body = string.Format("Details of the exceptions are: \n{0}", ex.Message), Footer = "Please look into this matter before the next notification cycle." });
                _auditService.UpdateAudit(new AuditViewModel() { Status = "DOWN", Comments = string.Format("Exception occured.", _affectedEvents), Id = 1 });
            }
        }
コード例 #12
0
        IPeriod CreatePeriod(DateTime dt, IDateTime referenceDate)
        {
            // Turn each resulting date/time into an IDateTime and associate it
            // with the reference date.
            IDateTime newDt = new iCalDateTime(dt, referenceDate.TzId);

            // NOTE: fixes bug #2938007 - hasTime missing
            newDt.HasTime = referenceDate.HasTime;

            newDt.AssociateWith(referenceDate);

            // Create a period from the new date/time.
            return(new Period(newDt));
        }
コード例 #13
0
 /// <summary>
 /// Updates a previously made appointment
 /// </summary>
 /// <param name="receiverEmail">The receivers email address</param>
 /// <param name="title">The event title</param>
 /// <param name="description">The event description</param>
 /// <param name="location">The event location</param>
 /// <param name="startDateTime">The event start time and date</param>
 /// <param name="endDateTime">The event end time and date</param>
 /// <param name="eventId">The event Unique Identifier</param>
 /// <param name="organizerName">The event organizer name</param>
 /// <param name="organizerEmail">The event organizer email, this will default to "*****@*****.**" if left empty</param>
 public static void UpdateAppointment(System.Net.Mail.MailMessage message,
     string location,
     string eventName,
     string eventId,
     iCalDateTime startDateTime,
     iCalDateTime endDateTime)
 {
     SendAppointment(message,
         location,
         eventName,
         eventId,
         startDateTime,
         endDateTime,
         true);
 }
コード例 #14
0
ファイル: iCalDateTime.cs プロジェクト: zumka/DDay.iCal
 public override bool Equals(object obj)
 {
     if (obj is IDateTime)
     {
         this.AssociateWith((IDateTime)obj);
         return(((IDateTime)obj).UTC.Equals(UTC));
     }
     else if (obj is DateTime)
     {
         iCalDateTime dt = (iCalDateTime)obj;
         this.AssociateWith(dt);
         return(object.Equals(dt.UTC, UTC));
     }
     return(false);
 }
コード例 #15
0
        /// <summary>
        /// Returns all occurrences of components of type T that start within the date range provided.
        /// All components occurring between <paramref name="startTime"/> and <paramref name="endTime"/>
        /// will be returned.
        /// </summary>
        /// <param name="startTime">The starting date range</param>
        /// <param name="endTime">The ending date range</param>
        virtual public List <Occurrence> GetOccurrences <T>(iCalDateTime startTime, iCalDateTime endTime) where T : RecurringComponent
        {
            List <Occurrence> occurrences = new List <Occurrence>();

            foreach (RecurringComponent rc in RecurringComponents)
            {
                if (rc is T)
                {
                    occurrences.AddRange(rc.GetOccurrences(startTime, endTime));
                }
            }

            occurrences.Sort();
            return(occurrences);
        }
コード例 #16
0
        private void EnsureProperties()
        {
            if (string.IsNullOrEmpty(UID))
            {
                // Create a new UID for the component
                UID = new UIDFactory().Build();
            }

            // NOTE: removed setting the 'CREATED' property here since it breaks serialization.
            // See https://sourceforge.net/projects/dday-ical/forums/forum/656447/topic/3754354
            if (DTStamp == null)
            {
                // Here, we don't simply set to DateTime.Now because DateTime.Now contains milliseconds, and
                // the iCalendar standard doesn't care at all about milliseconds.  Therefore, when comparing
                // two calendars, one generated, and one loaded from file, they may be functionally identical,
                // but be determined to be different due to millisecond differences.
                DateTime now = DateTime.Now;
                DTStamp = new iCalDateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);                
            }            
        }
コード例 #17
0
        private void EnsureProperties()
        {            
            if (string.IsNullOrEmpty(UID))
            {
                // Create a new UID for the component
                UID = new UIDFactory().Build();
            }

            if (!Properties.ContainsKey("SEQUENCE"))
                Sequence = 0;

            if (Created == null)
            {
                // Here, we don't simply set to DateTime.Now because DateTime.Now contains milliseconds, and
                // the iCalendar standard doesn't care at all about milliseconds.  Therefore, when comparing
                // two calendars, one generated, and one loaded from file, they may be functionally identical,
                // but be determined to be different due to millisecond differences.
                DateTime now = DateTime.Now;
                Created = new iCalDateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);                
            }

            if (DTStamp == null)
                DTStamp = Created.Copy<IDateTime>();
        }
コード例 #18
0
ファイル: iCalTimeZone.cs プロジェクト: logikonline/DDay.iCal
        public static iCalTimeZone FromSystemTimeZone(System.TimeZoneInfo tzinfo, DateTime earlistDateTimeToSupport, bool includeHistoricalData)
        {
            var adjustmentRules = tzinfo.GetAdjustmentRules();
            var utcOffset = tzinfo.BaseUtcOffset;
            var dday_tz = new iCalTimeZone();
            dday_tz.TZID = tzinfo.Id;

            IDateTime earliest = new iCalDateTime(earlistDateTimeToSupport);
            foreach (var adjustmentRule in adjustmentRules)
            {
                // Only include historical data if asked to do so.  Otherwise,
                // use only the most recent adjustment rule available.
                if (!includeHistoricalData && adjustmentRule.DateEnd < earlistDateTimeToSupport)
                    continue;

                var delta = adjustmentRule.DaylightDelta;
                var dday_tzinfo_standard = new DDay.iCal.iCalTimeZoneInfo();
                dday_tzinfo_standard.Name = "STANDARD";
                dday_tzinfo_standard.TimeZoneName = tzinfo.StandardName;
                dday_tzinfo_standard.Start = new iCalDateTime(new DateTime(adjustmentRule.DateStart.Year, adjustmentRule.DaylightTransitionEnd.Month, adjustmentRule.DaylightTransitionEnd.Day, adjustmentRule.DaylightTransitionEnd.TimeOfDay.Hour, adjustmentRule.DaylightTransitionEnd.TimeOfDay.Minute, adjustmentRule.DaylightTransitionEnd.TimeOfDay.Second).AddDays(1));
                if (dday_tzinfo_standard.Start.LessThan(earliest))
                    dday_tzinfo_standard.Start = dday_tzinfo_standard.Start.AddYears(earliest.Year - dday_tzinfo_standard.Start.Year);
                dday_tzinfo_standard.OffsetFrom = new UTCOffset(utcOffset + delta);
                dday_tzinfo_standard.OffsetTo = new UTCOffset(utcOffset);
                PopulateiCalTimeZoneInfo(dday_tzinfo_standard, adjustmentRule.DaylightTransitionEnd, adjustmentRule.DateStart.Year);

                // Add the "standard" time rule to the time zone
                dday_tz.AddChild(dday_tzinfo_standard);

                if (tzinfo.SupportsDaylightSavingTime)
                {
                    var dday_tzinfo_daylight = new DDay.iCal.iCalTimeZoneInfo();
                    dday_tzinfo_daylight.Name = "DAYLIGHT";
                    dday_tzinfo_daylight.TimeZoneName = tzinfo.DaylightName;
                    dday_tzinfo_daylight.Start = new iCalDateTime(new DateTime(adjustmentRule.DateStart.Year, adjustmentRule.DaylightTransitionStart.Month, adjustmentRule.DaylightTransitionStart.Day, adjustmentRule.DaylightTransitionStart.TimeOfDay.Hour, adjustmentRule.DaylightTransitionStart.TimeOfDay.Minute, adjustmentRule.DaylightTransitionStart.TimeOfDay.Second));
                    if (dday_tzinfo_daylight.Start.LessThan(earliest))
                        dday_tzinfo_daylight.Start = dday_tzinfo_daylight.Start.AddYears(earliest.Year - dday_tzinfo_daylight.Start.Year);
                    dday_tzinfo_daylight.OffsetFrom = new UTCOffset(utcOffset);
                    dday_tzinfo_daylight.OffsetTo = new UTCOffset(utcOffset + delta);
                    PopulateiCalTimeZoneInfo(dday_tzinfo_daylight, adjustmentRule.DaylightTransitionStart, adjustmentRule.DateStart.Year);

                    // Add the "daylight" time rule to the time zone
                    dday_tz.AddChild(dday_tzinfo_daylight);
                }                
            }

            // If no time zone information was recorded, at least
            // add a STANDARD time zone element to indicate the
            // base time zone information.
            if (dday_tz.TimeZoneInfos.Count == 0)
            {
                var dday_tzinfo_standard = new DDay.iCal.iCalTimeZoneInfo();
                dday_tzinfo_standard.Name = "STANDARD";
                dday_tzinfo_standard.TimeZoneName = tzinfo.StandardName;
                dday_tzinfo_standard.Start = earliest;                
                dday_tzinfo_standard.OffsetFrom = new UTCOffset(utcOffset);
                dday_tzinfo_standard.OffsetTo = new UTCOffset(utcOffset);

                // Add the "standard" time rule to the time zone
                dday_tz.AddChild(dday_tzinfo_standard);
            }

            return dday_tz;
        }
コード例 #19
0
        public ActionResult GiveMySchedule(int id)
        {
            List<ClassHour> UserClassHours = new List<ClassHour>();
            string role = (string)Session["selectedRoles"];
            if (role.Equals("instructor"))
            {
                var InstructorClasses = repository.GetInstructorRoster(id).ToList();
                foreach (var c in InstructorClasses)
                {
                    var classHours = repository.GetClassHoursList(c.ClassID).ToList();
                    foreach (var h in classHours)
                    {
                        UserClassHours.Add(h);
                    }
                }
            }
            else if (role.Equals("student"))
            {
                var StudentClasses = repository.GetEnrolledClasses(id).ToList();
                foreach (var c in StudentClasses)
                {
                    var classHours = repository.GetClassHoursList(c.ClassID).ToList();
                    foreach (var h in classHours)
                    {
                        UserClassHours.Add(h);
                    }
                }
            }

            DDay.iCal.iCalendar iCal = new DDay.iCal.iCalendar();

            // Create the event, and add it to the iCalendar

            foreach(var h in UserClassHours)
            {
                StringBuilder des = new StringBuilder();
                // Set information about the event
                Event evt = iCal.Create<Event>();
                //evt.Start.Add(h.startTime);

                //
                IRecurrencePattern pattern = new RecurrencePattern();
                pattern.Frequency = FrequencyType.Weekly; // Weekly
                pattern.Interval = 1; // Every 1
                pattern.ByDay.Add(new WeekDay(h.day)); //
                pattern.Until = h.Class.EndDate;
                iCalDateTime Date = new iCalDateTime(h.Class.StartDate);

                evt.RecurrenceRules.Add(pattern);
                evt.Start = Date.AddHours(h.startTime.Hours);
                evt.End = Date.AddHours(h.endTime.Hours);
                des.Append(" -Session ID: " + h.id);
                des.Append(" -Istructor: " + h.Class.Instructor);
                des.Append(" -Course Name: " + h.Class.Course.Title);
                evt.Description = des.ToString();
                evt.Location = h.location;
                evt.Summary = "Class 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, "MySchedule.ics");
        }
コード例 #20
0
        private IRecurrencePattern ProcessRecurrencePattern(IDateTime referenceDate)
        {
            RecurrencePattern r = new RecurrencePattern();
            r.CopyFrom(Pattern);

            // Convert the UNTIL value to a local date/time based on the time zone information that
            // is in the reference date
            if (r.Until != DateTime.MinValue)
            {
                // Build an iCalDateTime with the correct time zone & calendar
                var until = new iCalDateTime(r.Until, referenceDate.TZID);
                until.AssociatedObject = referenceDate.AssociatedObject;

                // Convert back to local time so time zone comparisons match
                r.Until = until.Local;
            }

            if (r.Frequency > FrequencyType.Secondly &&
                r.BySecond.Count == 0 &&
                referenceDate.HasTime /* NOTE: Fixes a bug where all-day events have BySecond/ByMinute/ByHour added incorrectly */)
                r.BySecond.Add(referenceDate.Second);
            if (r.Frequency > FrequencyType.Minutely &&
                r.ByMinute.Count == 0 &&
                referenceDate.HasTime /* NOTE: Fixes a bug where all-day events have BySecond/ByMinute/ByHour added incorrectly */)
                r.ByMinute.Add(referenceDate.Minute);
            if (r.Frequency > FrequencyType.Hourly &&
                r.ByHour.Count == 0 &&
                referenceDate.HasTime /* NOTE: Fixes a bug where all-day events have BySecond/ByMinute/ByHour added incorrectly */)
                r.ByHour.Add(referenceDate.Hour);

            // If BYDAY, BYYEARDAY, or BYWEEKNO is specified, then
            // we don't default BYDAY, BYMONTH or BYMONTHDAY
            if (r.ByDay.Count == 0)
            {
                // If the frequency is weekly, use the original date's day of week.
                // NOTE: fixes WeeklyCount1() and WeeklyUntil1() handling
                // If BYWEEKNO is specified and BYMONTHDAY/BYYEARDAY is not specified,
                // then let's add BYDAY to BYWEEKNO.
                // NOTE: fixes YearlyByWeekNoX() handling
                if (r.Frequency == FrequencyType.Weekly ||
                    (
                        r.ByWeekNo.Count > 0 &&
                        r.ByMonthDay.Count == 0 &&
                        r.ByYearDay.Count == 0
                    ))
                    r.ByDay.Add(new WeekDay(referenceDate.DayOfWeek));

                // If BYMONTHDAY is not specified,
                // default to the current day of month.
                // NOTE: fixes YearlyByMonth1() handling, added BYYEARDAY exclusion
                // to fix YearlyCountByYearDay1() handling
                if (r.Frequency > FrequencyType.Weekly &&
                    r.ByWeekNo.Count == 0 &&
                    r.ByYearDay.Count == 0 &&
                    r.ByMonthDay.Count == 0)
                    r.ByMonthDay.Add(referenceDate.Day);

                // If BYMONTH is not specified, default to
                // the current month.
                // NOTE: fixes YearlyCountByYearDay1() handling
                if (r.Frequency > FrequencyType.Monthly &&
                    r.ByWeekNo.Count == 0 &&
                    r.ByYearDay.Count == 0 &&
                    r.ByMonth.Count == 0)
                    r.ByMonth.Add(referenceDate.Month);
            }

            return r;
        }
コード例 #21
0
        public static iCalTimeZone FromSystemTimeZone(System.TimeZoneInfo tzinfo, DateTime earlistDateTimeToSupport, bool includeHistoricalData)
        {
            var adjustmentRules = tzinfo.GetAdjustmentRules();
            var utcOffset       = tzinfo.BaseUtcOffset;
            var dday_tz         = new iCalTimeZone();

            dday_tz.TZID = tzinfo.Id;

            IDateTime earliest = new iCalDateTime(earlistDateTimeToSupport);

            foreach (var adjustmentRule in adjustmentRules)
            {
                // Only include historical data if asked to do so.  Otherwise,
                // use only the most recent adjustment rule available.
                if (!includeHistoricalData && adjustmentRule.DateEnd < earlistDateTimeToSupport)
                {
                    continue;
                }

                var delta = adjustmentRule.DaylightDelta;
                var dday_tzinfo_standard = new DDay.iCal.iCalTimeZoneInfo();
                dday_tzinfo_standard.Name         = "STANDARD";
                dday_tzinfo_standard.TimeZoneName = tzinfo.StandardName;
                dday_tzinfo_standard.Start        = new iCalDateTime(new DateTime(adjustmentRule.DateStart.Year, adjustmentRule.DaylightTransitionEnd.Month, adjustmentRule.DaylightTransitionEnd.Day, adjustmentRule.DaylightTransitionEnd.TimeOfDay.Hour, adjustmentRule.DaylightTransitionEnd.TimeOfDay.Minute, adjustmentRule.DaylightTransitionEnd.TimeOfDay.Second).AddDays(1));
                if (dday_tzinfo_standard.Start.LessThan(earliest))
                {
                    dday_tzinfo_standard.Start = dday_tzinfo_standard.Start.AddYears(earliest.Year - dday_tzinfo_standard.Start.Year);
                }
                dday_tzinfo_standard.OffsetFrom = new UTCOffset(utcOffset + delta);
                dday_tzinfo_standard.OffsetTo   = new UTCOffset(utcOffset);
                PopulateiCalTimeZoneInfo(dday_tzinfo_standard, adjustmentRule.DaylightTransitionEnd, adjustmentRule.DateStart.Year);

                // Add the "standard" time rule to the time zone
                dday_tz.AddChild(dday_tzinfo_standard);

                if (tzinfo.SupportsDaylightSavingTime)
                {
                    var dday_tzinfo_daylight = new DDay.iCal.iCalTimeZoneInfo();
                    dday_tzinfo_daylight.Name         = "DAYLIGHT";
                    dday_tzinfo_daylight.TimeZoneName = tzinfo.DaylightName;
                    dday_tzinfo_daylight.Start        = new iCalDateTime(new DateTime(adjustmentRule.DateStart.Year, adjustmentRule.DaylightTransitionStart.Month, adjustmentRule.DaylightTransitionStart.Day, adjustmentRule.DaylightTransitionStart.TimeOfDay.Hour, adjustmentRule.DaylightTransitionStart.TimeOfDay.Minute, adjustmentRule.DaylightTransitionStart.TimeOfDay.Second));
                    if (dday_tzinfo_daylight.Start.LessThan(earliest))
                    {
                        dday_tzinfo_daylight.Start = dday_tzinfo_daylight.Start.AddYears(earliest.Year - dday_tzinfo_daylight.Start.Year);
                    }
                    dday_tzinfo_daylight.OffsetFrom = new UTCOffset(utcOffset);
                    dday_tzinfo_daylight.OffsetTo   = new UTCOffset(utcOffset + delta);
                    PopulateiCalTimeZoneInfo(dday_tzinfo_daylight, adjustmentRule.DaylightTransitionStart, adjustmentRule.DateStart.Year);

                    // Add the "daylight" time rule to the time zone
                    dday_tz.AddChild(dday_tzinfo_daylight);
                }
            }

            // If no time zone information was recorded, at least
            // add a STANDARD time zone element to indicate the
            // base time zone information.
            if (dday_tz.TimeZoneInfos.Count == 0)
            {
                var dday_tzinfo_standard = new DDay.iCal.iCalTimeZoneInfo();
                dday_tzinfo_standard.Name         = "STANDARD";
                dday_tzinfo_standard.TimeZoneName = tzinfo.StandardName;
                dday_tzinfo_standard.Start        = earliest;
                dday_tzinfo_standard.OffsetFrom   = new UTCOffset(utcOffset);
                dday_tzinfo_standard.OffsetTo     = new UTCOffset(utcOffset);

                // Add the "standard" time rule to the time zone
                dday_tz.AddChild(dday_tzinfo_standard);
            }

            return(dday_tz);
        }
コード例 #22
0
 /// <summary>
 /// Returns all occurrences of components of type T that start on the date provided.
 /// All components starting between 12:00:00AM and 11:59:59 PM will be
 /// returned.
 /// <note>
 /// This will first Evaluate() the date range required in order to
 /// determine the occurrences for the date provided, and then return
 /// the occurrences.
 /// </note>
 /// </summary>
 /// <param name="dt">The date for which to return occurrences.</param>
 /// <returns>A list of Periods representing the occurrences of this object.</returns>
 virtual public List <Occurrence> GetOccurrences <T>(iCalDateTime dt) where T : RecurringComponent
 {
     return(GetOccurrences <T>(dt.Local.Date, dt.Local.Date.AddDays(1).AddSeconds(-1)));
 }
コード例 #23
0
 /// <summary>
 /// Returns a list of occurrences of each recurring component
 /// for the date provided (<paramref name="dt"/>).
 /// </summary>
 /// <param name="dt">The date for which to return occurrences. Time is ignored on this parameter.</param>
 /// <returns>A list of occurrences that occur on the given date (<paramref name="dt"/>).</returns>
 public List <Occurrence> GetOccurrences(iCalDateTime dt)
 {
     return(GetOccurrences(dt.Local.Date, dt.Local.Date.AddDays(1).AddSeconds(-1)));
 }
コード例 #24
0
        private IRecurrencePattern ProcessRecurrencePattern(IDateTime referenceDate)
        {
            RecurrencePattern r = new RecurrencePattern();

            r.CopyFrom(Pattern);

            // Convert the UNTIL value to a local date/time based on the time zone information that
            // is in the reference date
            if (r.Until != DateTime.MinValue)
            {
                // Build an iCalDateTime with the correct time zone & calendar
                var until = new iCalDateTime(r.Until, referenceDate.TZID);
                until.AssociatedObject = referenceDate.AssociatedObject;

                // Convert back to local time so time zone comparisons match
                r.Until = until.Local;
            }

            if (r.Frequency > FrequencyType.Secondly &&
                r.BySecond.Count == 0 &&
                referenceDate.HasTime /* NOTE: Fixes a bug where all-day events have BySecond/ByMinute/ByHour added incorrectly */)
            {
                r.BySecond.Add(referenceDate.Second);
            }
            if (r.Frequency > FrequencyType.Minutely &&
                r.ByMinute.Count == 0 &&
                referenceDate.HasTime /* NOTE: Fixes a bug where all-day events have BySecond/ByMinute/ByHour added incorrectly */)
            {
                r.ByMinute.Add(referenceDate.Minute);
            }
            if (r.Frequency > FrequencyType.Hourly &&
                r.ByHour.Count == 0 &&
                referenceDate.HasTime /* NOTE: Fixes a bug where all-day events have BySecond/ByMinute/ByHour added incorrectly */)
            {
                r.ByHour.Add(referenceDate.Hour);
            }

            // If BYDAY, BYYEARDAY, or BYWEEKNO is specified, then
            // we don't default BYDAY, BYMONTH or BYMONTHDAY
            if (r.ByDay.Count == 0)
            {
                // If the frequency is weekly, use the original date's day of week.
                // NOTE: fixes WeeklyCount1() and WeeklyUntil1() handling
                // If BYWEEKNO is specified and BYMONTHDAY/BYYEARDAY is not specified,
                // then let's add BYDAY to BYWEEKNO.
                // NOTE: fixes YearlyByWeekNoX() handling
                if (r.Frequency == FrequencyType.Weekly ||
                    (
                        r.ByWeekNo.Count > 0 &&
                        r.ByMonthDay.Count == 0 &&
                        r.ByYearDay.Count == 0
                    ))
                {
                    r.ByDay.Add(new WeekDay(referenceDate.DayOfWeek));
                }

                // If BYMONTHDAY is not specified,
                // default to the current day of month.
                // NOTE: fixes YearlyByMonth1() handling, added BYYEARDAY exclusion
                // to fix YearlyCountByYearDay1() handling
                if (r.Frequency > FrequencyType.Weekly &&
                    r.ByWeekNo.Count == 0 &&
                    r.ByYearDay.Count == 0 &&
                    r.ByMonthDay.Count == 0)
                {
                    r.ByMonthDay.Add(referenceDate.Day);
                }

                // If BYMONTH is not specified, default to
                // the current month.
                // NOTE: fixes YearlyCountByYearDay1() handling
                if (r.Frequency > FrequencyType.Monthly &&
                    r.ByWeekNo.Count == 0 &&
                    r.ByYearDay.Count == 0 &&
                    r.ByMonth.Count == 0)
                {
                    r.ByMonth.Add(referenceDate.Month);
                }
            }

            return(r);
        }
コード例 #25
0
        // clone the DDay.iCal event, update dtstart (and maybe dtend) with Year/Month/Day for this occurrence
        public static DDay.iCal.Event PeriodizeRecurringEvent(DDay.iCal.Event evt, IPeriod period)
        {
            var kind = evt.Start.IsUniversalTime ? DateTimeKind.Utc : DateTimeKind.Local;

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

            var idtstart = new iCalDateTime(dtstart);

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

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

                idtend = new iCalDateTime(dtend);
            }

            var instance = new DDay.iCal.Event();
            instance.Start = idtstart;
            instance.End = idtend;
            instance.Summary = evt.Summary;
            instance.Description = evt.Description;
            foreach (var cat in evt.Categories)
                instance.Categories.Add(cat);
            instance.Location = evt.Location;
            instance.GeographicLocation = evt.GeographicLocation;
            instance.UID = evt.UID;
            instance.Url = evt.Url;
            return instance;
        }
コード例 #26
0
ファイル: PeriodList.cs プロジェクト: MaitreDede/dday-ical
        public List<Period> Evaluate(iCalDateTime StartDate, iCalDateTime FromDate, iCalDateTime EndDate)
        {
            List<Period> periods = new List<Period>();

            if (StartDate > FromDate)
                FromDate = StartDate;

            if (EndDate < FromDate ||
                FromDate > EndDate)
                return periods;

            foreach (Period p in Periods)
                if (!periods.Contains(p))
                    periods.Add(p);

            return periods;
        }
コード例 #27
0
 /// <summary>
 /// Evaluates component recurrences for the given range of time.
 /// <example>
 ///     For example, if you are displaying a month-view for January 2007,
 ///     you would want to evaluate recurrences for Jan. 1, 2007 to Jan. 31, 2007
 ///     to display relevant information for those dates.
 /// </example>
 /// </summary>
 /// <param name="FromDate">The beginning date/time of the range to test.</param>
 /// <param name="ToDate">The end date/time of the range to test.</param>
 public void Evaluate(iCalDateTime FromDate, iCalDateTime ToDate)
 {
     Evaluate <object>(FromDate, ToDate);
 }
コード例 #28
0
ファイル: iCalDateTime.cs プロジェクト: SpivEgin/ndef-nfc
        public void AssociateWith(IDateTime dt)
        {
            if (AssociatedObject == null && dt.AssociatedObject != null)
                AssociatedObject = dt.AssociatedObject;
            else if (AssociatedObject != null && dt.AssociatedObject == null)
                dt.AssociatedObject = AssociatedObject;

            // If these share the same TZID, then let's see if we
            // can share the time zone observance also!
            if (TimeZoneName != null && string.Equals(TimeZoneName, dt.TimeZoneName))
            {
                if (TimeZoneObservance != null && dt.TimeZoneObservance == null)
                {
                    IDateTime normalizedDt = new iCalDateTime(TimeZoneObservance.Value.TimeZoneInfo.OffsetTo.ToUTC(dt.Value));
                    if (TimeZoneObservance.Value.Contains(normalizedDt))
                        dt.TimeZoneObservance = TimeZoneObservance;
                }
                else if (dt.TimeZoneObservance != null && TimeZoneObservance == null)
                {
                    IDateTime normalizedDt = new iCalDateTime(dt.TimeZoneObservance.Value.TimeZoneInfo.OffsetTo.ToUTC(Value));
                    if (dt.TimeZoneObservance.Value.Contains(normalizedDt))
                        TimeZoneObservance = dt.TimeZoneObservance;
                }
            }
        }
コード例 #29
0
ファイル: iCalDateTime.cs プロジェクト: SpivEgin/ndef-nfc
 public override bool Equals(object obj)
 {
     if (obj is IDateTime)
     {
         this.AssociateWith((IDateTime)obj);
         return ((IDateTime)obj).UTC.Equals(UTC);
     }
     else if (obj is DateTime)
     {
         iCalDateTime dt = new iCalDateTime((DateTime)obj);
         this.AssociateWith(dt);
         return object.Equals(dt.UTC, UTC);
     }
     return false;
 }
コード例 #30
0
        public ActionResult EmailMySchedule(int id)
        {
            List<ClassHour> UserClassHours = new List<ClassHour>();
            string role = (string)Session["selectedRoles"];
            if (role.Equals("instructor"))
            {
                var InstructorClasses = repository.GetInstructorRoster(id).ToList();
                foreach (var c in InstructorClasses)
                {
                    var classHours = repository.GetClassHoursList(c.ClassID).ToList();
                    foreach (var h in classHours)
                    {
                        UserClassHours.Add(h);
                    }
                }
            }
            else if (role.Equals("student"))
            {
                var StudentClasses = repository.GetEnrolledClasses(id).ToList();
                foreach (var c in StudentClasses)
                {
                    var classHours = repository.GetClassHoursList(c.ClassID).ToList();
                    foreach (var h in classHours)
                    {
                        UserClassHours.Add(h);
                    }
                }
            }

            DDay.iCal.iCalendar iCal = new DDay.iCal.iCalendar();

            // Create the event, and add it to the iCalendar

            foreach (var h in UserClassHours)
            {
                StringBuilder des = new StringBuilder();
                // Set information about the event
                Event evt = iCal.Create<Event>();
                //evt.Start.Add(h.startTime);

                //
                IRecurrencePattern pattern = new RecurrencePattern();
                pattern.Frequency = FrequencyType.Weekly; // Weekly
                pattern.Interval = 1; // Every 1
                pattern.ByDay.Add(new WeekDay(h.day)); //
                pattern.Until = h.Class.EndDate;
                iCalDateTime Date = new iCalDateTime(h.Class.StartDate);

                evt.RecurrenceRules.Add(pattern);
                evt.Start = Date.AddHours(h.startTime.Hours);
                evt.End = Date.AddHours(h.endTime.Hours);
                des.Append(" -Session ID: " + h.id);
                des.Append(" -Istructor: " + h.Class.Instructor);
                des.Append(" -Course Name: " + h.Class.Course.Title);
                evt.Description = des.ToString();
                evt.Location = h.location;
                evt.Summary = "Class 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);
            MemoryStream stream = new MemoryStream(bytes);

            var MySmtp = repository.Smtp.First();
            var user = repository.Users.FirstOrDefault(u => u.userName == User.Identity.Name);
            // send notification email through gmail
            // email address "*****@*****.**"
            // password "P@ttersonetsemail" (Patterson employee training system email)
            System.Net.Mail.MailMessage email = new System.Net.Mail.MailMessage();
            email.To.Add(user.email);
            email.Subject = "Your schedule from P.E.T.S";
            var fromAddress = new MailAddress(MySmtp.user);
            email.From = fromAddress;
            email.Body = "This is the schedule for " + user.name + " that has been requested, Thank you.";
            System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(stream, "MySchedule.ics", contentType);
            email.Attachments.Add(attachment);
            System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(MySmtp.server);
            smtp.UseDefaultCredentials = false;
            smtp.Credentials = new System.Net.NetworkCredential(fromAddress.Address, MySmtp.password);
            smtp.EnableSsl = true;
            smtp.Port = MySmtp.port;
            smtp.Send(email);
            TempData["message"] = string.Format("Your schedule has been sent to {0} .", user.email);
            return RedirectToAction("Index", "Home");
        }
コード例 #31
0
ファイル: Program.cs プロジェクト: TotallWAR/schedule
        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);
        }
コード例 #32
0
 public void iCalSingleEventIsFuture()
 {
     var ics = basic_ics;
     var futuredate = DateTime.Now + new TimeSpan(10, 0, 0, 0, 0);
     ics = ics.Replace("__SINGLE_DATE_START__", futuredate.ToString("yyyyMMdd"));
     ics = ics.Replace("__SINGLE_DATE_END__", futuredate.ToString("yyyyMMdd"));
     StringReader sr = new StringReader(ics);
     var ical = iCalendar.LoadFromStream(sr).First().Calendar;
     var evt = ical.Events[0];
     var ical_now = new iCalDateTime(DateTime.Now.ToUniversalTime());
     Assert.That(evt.GetOccurrences(ical_now).Count == 0);
     var collector = new Collector(test_calinfo, settings);
     Assert.IsTrue(Collector.IsCurrentOrFutureDTStartInTz(evt.Start.Date, test_calinfo.tzinfo));
 }
コード例 #33
0
 public static bool IsCurrentOrFutureDTStartInTz(iCalDateTime ical_dtstart, TimeZoneInfo tzinfo)
 {
     var utc_last_midnight = Utils.MidnightInTz(tzinfo);
     return ical_dtstart.UTC >= utc_last_midnight.UniversalTime;
 }
コード例 #34
0
 public void Evaluate <T>(iCalDateTime FromDate, iCalDateTime ToDate)
 {
     throw new NotSupportedException("Evaluate() is no longer supported as a public method.  Use GetOccurrences() instead.");
 }
コード例 #35
0
        /// <summary>
        /// Sends an email with an appointment to a receiver
        /// </summary>
        /// <param name="receiverEmail">The receivers email address</param>
        /// <param name="title">The event title</param>
        /// <param name="description">The event description</param>
        /// <param name="location">The event location</param>
        /// <param name="startDateTime">The event start time and date</param>
        /// <param name="endDateTime">The event end time and date</param>
        /// <param name="eventId">The event Unique Identifier</param>
        /// <param name="updateEvent">If this is an update for a previously sent event you can update the previously sent event by setting this paramter to <c>true</c></param>
        /// <param name="organizerName">The event organizer name</param>
        /// <param name="organizerEmail">The event organizer email, this will default to "*****@*****.**" if left empty</param>
        private static void SendAppointment(System.Net.Mail.MailMessage message,
            string location,
            string eventName,
            string eventId,
            iCalDateTime startDateTime,
            iCalDateTime endDateTime,
            bool updateEvent)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            using (iCalendar iCal = new iCalendar())
            {
                // outlook 2003 needs this property,
                // or we'll get an error (a Lunar error!)
                // "REQUEST" will update an existing event with the same
                // UID (Unique ID) and a newer time stamp.
                if (updateEvent)
                {
                    iCal.Method = "REQUEST";
                }
                else
                {
                    iCal.Method = "PUBLISH";
                }

                // Create the event
                Event evt = iCal.Create<Event>();
                evt.Summary = eventName;
                evt.Start = startDateTime;
                evt.End = endDateTime;
                evt.Description = string.Format("Agenda afspraak voor '{0}'", eventName);
                evt.Location = location;
                evt.IsAllDay = false;
                evt.Organizer = new Organizer(string.Concat("MAILTO:", message.From.Address));//organizer is mandatory for outlook 2007
                if (!string.IsNullOrWhiteSpace(message.From.DisplayName))
                {
                    evt.Organizer.Parameters.Add("CN", message.From.DisplayName);
                }
                evt.UID = eventId;
                evt.Status = EventStatus.Confirmed;
                evt.Priority = 5;//MEDIUM

                iCalendarSerializer serializer = new iCalendarSerializer();

                try
                {
                    //Add the attachment, specify it is a calendar file.
                    using (System.Net.Mail.Attachment attachment = System.Net.Mail.Attachment.CreateAttachmentFromString(serializer.SerializeToString(iCal), new ContentType("text/calendar")))
                    {
                        attachment.TransferEncoding = TransferEncoding.Base64;
                        attachment.Name = "EventDetails.ics"; //not visible in outlook
                        message.Attachments.Add(attachment);
                        using (SmtpClient smtpClient = new SmtpClient())
                        {
                            smtpClient.Send(message);
                        }
                    }
                }
                catch { }
            }
        }
コード例 #36
0
 /// <summary>
 /// Returns a list of occurrences of each recurring component
 /// that occur between <paramref name="FromDate"/> and <paramref name="ToDate"/>.
 /// </summary>
 /// <param name="FromDate">The beginning date/time of the range.</param>
 /// <param name="ToDate">The end date/time of the range.</param>
 /// <returns>A list of occurrences that fall between the dates provided.</returns>
 public List <Occurrence> GetOccurrences(iCalDateTime FromDate, iCalDateTime ToDate)
 {
     return(GetOccurrences <RecurringComponent>(FromDate, ToDate));
 }
コード例 #37
0
 protected IDateTime ConvertToIDateTime(DateTime dt, IDateTime referenceDate)
 {
     IDateTime newDt = new iCalDateTime(dt, referenceDate.TZID);
     newDt.AssociateWith(referenceDate);
     return newDt;
 }
コード例 #38
0
ファイル: Episode.cs プロジェクト: stufkan/ShowRSSCalendar
 public Episode(string seriesTitle, string episodeTitle, iCalDateTime date)
 {
     this.seriesTitle = seriesTitle;
     this.episodeTitle = episodeTitle;
     this.date = date;
 }
コード例 #39
0
        public override IList<IPeriod> Evaluate(IDateTime referenceDate, DateTime periodStart, DateTime periodEnd, bool includeReferenceDateInResults)
        {
            // Create a recurrence pattern suitable for use during evaluation.
            IRecurrencePattern pattern = ProcessRecurrencePattern(referenceDate);

            // Enforce evaluation restrictions on the pattern.
            EnforceEvaluationRestrictions(pattern);

            Periods.Clear();
            foreach (DateTime dt in GetDates(referenceDate, periodStart, periodEnd, -1, pattern, includeReferenceDateInResults))
            {
                // Turn each resulting date/time into an IDateTime and associate it
                // with the reference date.
                IDateTime newDt = new iCalDateTime(dt, referenceDate.TZID);
                
                // NOTE: fixes bug #2938007 - hasTime missing
                newDt.HasTime = referenceDate.HasTime;

                newDt.AssociateWith(referenceDate);

                // Create a period from the new date/time.
                IPeriod p = new Period(newDt);
                
                if (!Periods.Contains(p))
                    Periods.Add(p);
            }

            return Periods;
        }
コード例 #40
0
        public ActionResult DeleteConfirmed(int id, string RemoveInstance, string StartDate, string EndDate)
        {
            GroupInstance groupinstance = db.GroupInstances.Find(id);
            if (!String.IsNullOrEmpty(RemoveInstance))
            {
                if (Convert.ToBoolean(RemoveInstance) == false)
                {
                    db.GroupInstances.Remove(groupinstance);
                }
                else
                {
                    iCalendarSerializer serializer = new iCalendarSerializer();
                    iCalendarCollection icalCollection = new iCalendarCollection();
                    using (TextReader tr = new StringReader(groupinstance.RecurrenceRule))
                    {
                        icalCollection = (iCalendarCollection)serializer.Deserialize(tr);
                    }

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

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

                    pl.Add(time);
                    ev.ExceptionDates.Add(pl);
                    iCalendar ical = new iCalendar();
                    ical.Events.Add(ev);
                    serializer = new iCalendarSerializer(ical);
                    groupinstance.RecurrenceRule = serializer.SerializeToString(ical);
                    db.Entry(groupinstance).State = EntityState.Modified;
                }
                db.SaveChanges();
            }
            else
            {
                    db.GroupInstances.Remove(groupinstance);
                    db.SaveChanges();
            }
            return Content(Boolean.TrueString);
        }
コード例 #41
0
ファイル: Program.cs プロジェクト: tyrelltle/TempProjectBag
        /// <summary>
        /// Displays the calendar in the time zone identified by <paramref name="tzid"/>.
        /// </summary>
        static void ShowCalendar(IICalendar iCal, string tzid)
        {
            IDateTime start = new iCalDateTime(2007, 3, 1);
            IDateTime end = new iCalDateTime(2007, 4, 1).AddSeconds(-1);

            IList<Occurrence> occurrences = iCal.GetOccurrences(start, end);

            Console.WriteLine("====Events/Todos/Journal Entries in " + tzid + "====");
            foreach (Occurrence o in occurrences)
            {
                IRecurringComponent rc = o.Source as IRecurringComponent;
                if (rc != null)
                {
                    Console.WriteLine(
                        o.Period.StartTime.ToTimeZone(tzid).ToString("ddd, MMM d - h:mm") + " to " +
                        o.Period.EndTime.ToTimeZone(tzid).ToString("h:mm tt") + Environment.NewLine +
                        rc.Summary + Environment.NewLine);
                }
            }

            Console.WriteLine("====Alarms in " + tzid + "====");
            foreach (object obj in iCal.Children)
            {
                IRecurringComponent rc = obj as IRecurringComponent;
                if (rc != null)
                {
                    foreach (AlarmOccurrence ao in rc.PollAlarms(start, end))
                    {
                        Console.WriteLine(
                            "Alarm: " +
                            ao.DateTime.ToTimeZone(tzid).ToString("ddd, MMM d - h:mm") + ": " +
                            ao.Alarm.Summary);
                    }
                }
            }

            Console.WriteLine();
        }
コード例 #42
0
        IPeriod CreatePeriod(DateTime dt, IDateTime referenceDate)
        {
            // Turn each resulting date/time into an IDateTime and associate it
            // with the reference date.
            IDateTime newDt = new iCalDateTime(dt, referenceDate.TZID);

            // NOTE: fixes bug #2938007 - hasTime missing
            newDt.HasTime = referenceDate.HasTime;

            newDt.AssociateWith(referenceDate);

            // Create a period from the new date/time.
            return new Period(newDt);
        }
コード例 #43
0
        virtual public TimeZoneObservance? GetObservance(IDateTime dt)
        {
            if (Parent == null)
                throw new Exception("Cannot call GetObservance() on a TimeZoneInfo whose Parent property is null.");

            // Normalize date/time values within this time zone to a UTC value.
            DateTime normalizedDt = dt.Value;
            if (string.Equals(dt.TZID, TZID))
            {
                dt = new iCalDateTime(OffsetTo.ToUTC(dt.Value));
                normalizedDt = OffsetTo.ToUTC(normalizedDt);
            }

            // Let's evaluate our time zone observances to find the 
            // observance that applies to this date/time value.
            IEvaluator parentEval = Parent.GetService(typeof(IEvaluator)) as IEvaluator;
            if (parentEval != null)
            {
                // Evaluate the date/time in question.
                parentEval.Evaluate(Start, DateUtil.GetSimpleDateTimeData(Start), normalizedDt, true);
                foreach (IPeriod period in m_Evaluator.Periods)
                {
                    if (period.Contains(dt))
                        return new TimeZoneObservance(period, this);
                }
            }
            return null;
        }