public override string SerializeToString(object obj)
 {
     try
     {
         ITrigger t = obj as ITrigger;
         if (t != null)
         {
             // Push the trigger onto the serialization stack
             SerializationContext.Push(t);
             try
             {
                 ISerializerFactory factory = GetService <ISerializerFactory>();
                 if (factory != null)
                 {
                     Type valueType = t.GetValueType() ?? typeof(TimeSpan);
                     IStringSerializer serializer = factory.Build(valueType, SerializationContext) as IStringSerializer;
                     if (serializer != null)
                     {
                         object value = (valueType == typeof(IDateTime)) ? (object)t.DateTime : (object)t.Duration;
                         return(serializer.SerializeToString(value));
                     }
                 }
             }
             finally
             {
                 // Pop the trigger off the serialization stack
                 SerializationContext.Pop();
             }
         }
         return(null);
     }
     catch
     {
         return(null);
     }
 }
Ejemplo n.º 2
0
        public override string SerializeToString(object obj)
        {
            IRecurrencePattern recur = obj as IRecurrencePattern;
            ISerializerFactory factory = GetService<ISerializerFactory>();
            if (recur != null && factory != null)
            {
                // Push the recurrence pattern onto the serialization stack
                SerializationContext.Push(recur);

                List<string> values = new List<string>();

                values.Add("FREQ=" + Enum.GetName(typeof(FrequencyType), recur.Frequency).ToUpper());

                //-- FROM RFC2445 --
                //The INTERVAL rule part contains a positive integer representing how
                //often the recurrence rule repeats. The default value is "1", meaning
                //every second for a SECONDLY rule, or every minute for a MINUTELY
                //rule, every hour for an HOURLY rule, every day for a DAILY rule,
                //every week for a WEEKLY rule, every month for a MONTHLY rule and
                //every year for a YEARLY rule.
                int interval = recur.Interval;
                if (interval == int.MinValue)
                    interval = 1;

                if (interval != 1)
                    values.Add("INTERVAL=" + interval);

                if (recur.Until != DateTime.MinValue)
                {
                    IStringSerializer serializer = factory.Build(typeof(IDateTime), SerializationContext) as IStringSerializer;
                    if (serializer != null)
                    {
                        IDateTime until = new iCalDateTime(recur.Until);
                        until.HasTime = true;
                        values.Add("UNTIL=" + serializer.SerializeToString(until));
                    }
                }

                if (recur.FirstDayOfWeek != DayOfWeek.Monday)
                    values.Add("WKST=" + Enum.GetName(typeof(DayOfWeek), recur.FirstDayOfWeek).ToUpper().Substring(0, 2));

                if (recur.Count != int.MinValue)
                    values.Add("COUNT=" + recur.Count);

                if (recur.ByDay.Count > 0)
                {
                    List<string> bydayValues = new List<string>();

                    IStringSerializer serializer = factory.Build(typeof(IWeekDay), SerializationContext) as IStringSerializer;
                    if (serializer != null)
                    {
                        foreach (WeekDay byday in recur.ByDay)
                            bydayValues.Add(serializer.SerializeToString(byday));
                    }

                    values.Add("BYDAY=" + string.Join(",", bydayValues.ToArray()));
                }

                SerializeByValue(values, recur.ByHour, "BYHOUR");
                SerializeByValue(values, recur.ByMinute, "BYMINUTE");
                SerializeByValue(values, recur.ByMonth, "BYMONTH");
                SerializeByValue(values, recur.ByMonthDay, "BYMONTHDAY");
                SerializeByValue(values, recur.BySecond, "BYSECOND");
                SerializeByValue(values, recur.BySetPosition, "BYSETPOS");
                SerializeByValue(values, recur.ByWeekNo, "BYWEEKNO");
                SerializeByValue(values, recur.ByYearDay, "BYYEARDAY");

                // Pop the recurrence pattern off the serialization stack
                SerializationContext.Pop();
                
                return Encode(recur, string.Join(";", values.ToArray()));
            }
            return null;
        }
Ejemplo n.º 3
0
        public override string SerializeToString(object obj)
        {
            ICalendarProperty prop = obj as ICalendarProperty;

            if (prop != null &&
                prop.Value != null)
            {
                // Don't serialize the property if the value is null

                // Push this object on the serialization context.
                SerializationContext.Push(prop);

                IDataTypeMapper mapper         = GetService <IDataTypeMapper>();
                Type            serializedType = mapper.GetPropertyMapping(prop);

                // Build a list of values that are to be serialized.
                List <object> objs = new List <object>();
                if (!(prop.Value is string) &&
                    !(typeof(IEnumerable <string>).IsAssignableFrom(serializedType)) &&
                    prop.Value is IEnumerable)
                {
                    foreach (object v in (IEnumerable)prop.Value)
                    {
                        objs.Add(v);
                    }
                }
                else
                {
                    objs.Add(prop.Value);
                }

                // Get a serializer factory that we can use to serialize
                // the property and parameter values
                ISerializerFactory sf = GetService <ISerializerFactory>();

                StringBuilder result = new StringBuilder();
                foreach (object v in objs)
                {
                    // Get a serializer to serialize the property's value.
                    // If we can't serialize the property's value, the next step is worthless anyway.
                    IStringSerializer valueSerializer = sf.Build(v.GetType(), SerializationContext) as IStringSerializer;
                    if (valueSerializer != null)
                    {
                        // Iterate through each value to be serialized,
                        // and give it a property (with parameters).
                        // FIXME: this isn't always the way this is accomplished.
                        // Multiple values can often be serialized within the
                        // same property.  How should we fix this?

                        // NOTE:
                        // We Serialize the property's value first, as during
                        // serialization it may modify our parameters.
                        // FIXME: the "parameter modification" operation should
                        // be separated from serialization. Perhaps something
                        // like PreSerialize(), etc.
                        string value = valueSerializer.SerializeToString(v);

                        // Get the list of parameters we'll be serializing
                        ICalendarParameterList parameterList = prop.Parameters;
                        if (v is ICalendarDataType)
                        {
                            parameterList = ((ICalendarDataType)v).Parameters;
                        }

                        StringBuilder sb = new StringBuilder(prop.Name);
                        if (parameterList.Count > 0)
                        {
                            // Get a serializer for parameters
                            IStringSerializer parameterSerializer = sf.Build(typeof(ICalendarParameter), SerializationContext) as IStringSerializer;
                            if (parameterSerializer != null)
                            {
                                // Serialize each parameter
                                List <string> parameters = new List <string>();
                                foreach (ICalendarParameter param in parameterList)
                                {
                                    parameters.Add(parameterSerializer.SerializeToString(param));
                                }

                                // Separate parameters with semicolons
                                sb.Append(";");
                                sb.Append(string.Join(";", parameters.ToArray()));
                            }
                        }
                        sb.Append(":");
                        sb.Append(value);

                        result.Append(TextUtil.WrapLines(sb.ToString()));
                    }
                }

                // Pop the object off the serialization context.
                SerializationContext.Pop();

                return(result.ToString());
            }
            return(null);
        }
Ejemplo n.º 4
0
 private string SerializeCalendar(IICalendar calendar)
 {
     return(_calendarSerializer.SerializeToString(calendar));
 }
Ejemplo n.º 5
0
        public ActionResult GetIcsForCalendar(int id)
        {
            DDay.iCal.iCalendar iCal = new DDay.iCal.iCalendar();


            var lctrl   = new LocationApiController();
            var calctrl = new CalendarApiController();
            var cal     = calctrl.GetById(id);

            EventLocation l = null;

            iCal.Properties.Add(new CalendarProperty("X-WR-CALNAME", cal.Calendarname));

            //Get normal events for calendar
            var nectrl = new EventApiController();

            foreach (var e in nectrl.GetAll().Where(x => x.calendarId == id))
            {
                // Create the event, and add it to the iCalendar
                DDay.iCal.Event evt = iCal.Create <DDay.iCal.Event>();

                var start = (DateTime)e.start;
                evt.Start = new iCalDateTime(start.ToUniversalTime());
                if (e.end != null)
                {
                    var end = (DateTime)e.end;
                    evt.End = new iCalDateTime(end.ToUniversalTime());
                }

                evt.Description = this.GetDescription(e, CultureInfo.CurrentCulture.ToString());
                evt.Summary     = e.title;
                evt.IsAllDay    = e.allDay;
                evt.Categories.AddRange(e.categories.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList());

                //If it has a location fetch it
                if (e.locationId != 0)
                {
                    l            = lctrl.GetById(e.locationId);
                    evt.Location = l.LocationName + "," + l.Street + "," + l.ZipCode + " " + l.City + "," + l.Country;
                    //evt.GeographicLocation = new GeographicLocation(Convert.ToDouble(l.lat,CultureInfo.InvariantCulture), Convert.ToDouble(l.lon, CultureInfo.InvariantCulture));
                }

                var attendes = new List <IAttendee>();

                if (e.Organisator != null && e.Organisator != 0)
                {
                    var       ms          = Services.MemberService;
                    var       member      = ms.GetById(e.Organisator);
                    string    attendee    = "MAILTO:" + member.Email;
                    IAttendee reqattendee = new DDay.iCal.Attendee(attendee)
                    {
                        CommonName = member.Name,
                        Role       = "REQ-PARTICIPANT"
                    };
                    attendes.Add(reqattendee);
                }

                if (attendes != null && attendes.Count > 0)
                {
                    evt.Attendees = attendes;
                }
            }

            //Get recurring events
            var rectrl = new REventApiController();

            foreach (var e in rectrl.GetAll().Where(x => x.calendarId == id))
            {
                // Create the event, and add it to the iCalendar
                DDay.iCal.Event evt = iCal.Create <DDay.iCal.Event>();

                evt.Description = this.GetDescription(e, CultureInfo.CurrentCulture.ToString());
                evt.Summary     = e.title;
                evt.IsAllDay    = e.allDay;
                evt.Categories.AddRange(e.categories.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList());

                //If it has a location fetch it
                if (e.locationId != 0)
                {
                    l            = lctrl.GetById(e.locationId);
                    evt.Location = l.LocationName + "," + l.Street + "," + l.ZipCode + " " + l.City + "," + l.Country;
                    //evt.GeographicLocation = new GeographicLocation(Convert.ToDouble(l.lat, CultureInfo.InvariantCulture), Convert.ToDouble(l.lon, CultureInfo.InvariantCulture));
                }

                RecurrencePattern rp = null;
                var frequency        = (FrequencyTypeEnum)e.frequency;
                switch (frequency)
                {
                case FrequencyTypeEnum.Daily:
                {
                    rp = new RecurrencePattern(FrequencyType.Daily);
                    break;
                }

                case FrequencyTypeEnum.Monthly:
                {
                    rp = new RecurrencePattern(FrequencyType.Monthly);
                    break;
                }

                case FrequencyTypeEnum.Weekly:
                {
                    rp = new RecurrencePattern(FrequencyType.Weekly);
                    break;
                }

                case FrequencyTypeEnum.Yearly:
                {
                    rp = new RecurrencePattern(FrequencyType.Yearly);
                    break;
                }

                default:
                {
                    rp = new RecurrencePattern(FrequencyType.Monthly);
                    break;
                }
                }
                switch (e.day)
                {
                case (int)DayOfWeekEnum.Mon:
                {
                    rp.ByDay.Add(new WeekDay(DayOfWeek.Monday));
                    break;
                }

                case (int)DayOfWeekEnum.Tue:
                {
                    rp.ByDay.Add(new WeekDay(DayOfWeek.Tuesday));
                    break;
                }

                case (int)DayOfWeekEnum.Wed:
                {
                    rp.ByDay.Add(new WeekDay(DayOfWeek.Wednesday));
                    break;
                }

                case (int)DayOfWeekEnum.Thu:
                {
                    rp.ByDay.Add(new WeekDay(DayOfWeek.Thursday));
                    break;
                }

                case (int)DayOfWeekEnum.Fri:
                {
                    rp.ByDay.Add(new WeekDay(DayOfWeek.Friday));
                    break;
                }

                case (int)DayOfWeekEnum.Sat:
                {
                    rp.ByDay.Add(new WeekDay(DayOfWeek.Saturday));
                    break;
                }

                case (int)DayOfWeekEnum.Sun:
                {
                    rp.ByDay.Add(new WeekDay(DayOfWeek.Sunday));
                    break;
                }
                }
                evt.RecurrenceRules.Add(rp);

                Schedule schedule = new Schedule(new ScheduleWidget.ScheduledEvents.Event()
                {
                    Title                  = e.title,
                    DaysOfWeekOptions      = (DayOfWeekEnum)e.day,
                    FrequencyTypeOptions   = (FrequencyTypeEnum)e.frequency,
                    MonthlyIntervalOptions = (MonthlyIntervalEnum)e.monthly_interval
                });

                var occurence = Convert.ToDateTime(schedule.NextOccurrence(DateTime.Now));
                evt.Start = new iCalDateTime(new DateTime(occurence.Year, occurence.Month, occurence.Day, e.start.Hour, e.start.Minute, 0));

                var attendes = new List <IAttendee>();

                if (e.Organisator != null && e.Organisator != 0)
                {
                    var       ms          = Services.MemberService;
                    var       member      = ms.GetById(e.Organisator);
                    string    attendee    = "MAILTO:" + member.Email;
                    IAttendee reqattendee = new DDay.iCal.Attendee(attendee)
                    {
                        CommonName = member.Name,
                        Role       = "REQ-PARTICIPANT"
                    };
                    attendes.Add(reqattendee);
                }

                if (attendes != null && attendes.Count > 0)
                {
                    evt.Attendees = attendes;
                }
            }

            // Create a serialization context and serializer factory.
            // These will be used to build the serializer for our object.
            ISerializationContext ctx     = new SerializationContext();
            ISerializerFactory    factory = new DDay.iCal.Serialization.iCalendar.SerializerFactory();
            // Get a serializer for our object
            IStringSerializer serializer = factory.Build(iCal.GetType(), ctx) as IStringSerializer;

            string output      = serializer.SerializeToString(iCal);
            var    contentType = "text/calendar";
            var    bytes       = Encoding.UTF8.GetBytes(output);

            return(File(bytes, contentType, cal.Calendarname + ".ics"));
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Function is called to create the course ics file
        /// Function is called everytime the course calendar needs to be updated
        /// </summary>
        /// <param name="id"></param>
        public void CreateCourseCalendar(int id)
        {
            //Get the Course
            var course = (from d in db.Courses
                          where d.ID == id
                          select new
            {
                d.StartDate,
                d.EndDate,
                d.Prefix,
                d.Number,
                d.Semester,
                d.Year,
                d.CourseMeetings,
                d.CourseBreaks,
                d.ID
            }).FirstOrDefault();


            //get course events
            var events = (from e in db.Events
                          where e.Poster.AbstractCourseID == ActiveCourseUser.AbstractCourseID &&
                          e.StartDate >= course.StartDate &&
                          e.StartDate <= course.EndDate &&
                          e.Approved
                          select new
            {
                e.StartDate,
                e.EndDate,
                e.Title,
                e.Description
            }).ToList();

            //Create the calendar object
            iCalendar courseCalendar = new iCalendar();

            //initalize the Calendar object
            courseCalendar.AddTimeZone(DateTimeExtensions.GetTimeZone(((Course)ActiveCourseUser.AbstractCourse).TimeZoneOffset));
            courseCalendar.Method    = "PUBLISH";
            courseCalendar.Name      = "VCALENDAR";
            courseCalendar.Version   = "2.0";
            courseCalendar.ProductID = "-//Washington State University//PLUS.OSBLE.org//EN";
            courseCalendar.Scale     = "GREGORIAN";
            courseCalendar.AddProperty("X-WR-CALNAME", course.Prefix + "-" + course.Number + "-" + course.Semester + "-" + course.Year);

            //get course breaks
            if (ActiveCourseUser.AbstractCourse is Course && ((ActiveCourseUser.AbstractCourse as Course).ShowMeetings == true))
            {
                foreach (CourseMeeting cm in course.CourseMeetings)
                {
                    StringBuilder rpPattern = new StringBuilder("FREQ=WEEKLY;UNTIL=");
                    rpPattern.Append(new iCalDateTime(course.EndDate.UTCToCourse(ActiveCourseUser.AbstractCourseID)).ToString(@"yyyyMMdd\THHmmss\Z"));
                    rpPattern.Append(";WKST=SU;BYDAY=");
                    if (cm.Sunday)
                    {
                        rpPattern.Append("SU,");
                    }
                    if (cm.Monday)
                    {
                        rpPattern.Append("MO,");
                    }
                    if (cm.Tuesday)
                    {
                        rpPattern.Append("TU,");
                    }
                    if (cm.Wednesday)
                    {
                        rpPattern.Append("WE,");
                    }
                    if (cm.Thursday)
                    {
                        rpPattern.Append("TH,");
                    }
                    if (cm.Friday)
                    {
                        rpPattern.Append("FR,");
                    }
                    if (cm.Saturday)
                    {
                        rpPattern.Append("SA");
                    }

                    //trim trailing comma if it is there
                    if (rpPattern[rpPattern.Length - 1] == ',')
                    {
                        rpPattern.Remove(rpPattern.Length - 1, 1);
                    }

                    RecurringComponent recurringComponent = new RecurringComponent();
                    RecurrencePattern  pattern            = new RecurrencePattern(rpPattern.ToString());

                    DDay.iCal.Event evt = courseCalendar.Create <DDay.iCal.Event>();
                    //may cause issues
                    DateTime evtStart = DateTime.SpecifyKind(course.StartDate, DateTimeKind.Utc);
                    evtStart = evtStart.Add(cm.StartTime.TimeOfDay);
                    DateTime evtEnd = DateTime.SpecifyKind(course.StartDate, DateTimeKind.Utc);
                    evtEnd = evtEnd.Add(cm.EndTime.TimeOfDay);

                    //we need to test if right NOW is in DST.
                    //case: course starts during DST, and it's now after DST, result: after DST event is now wrong.
                    DateTime currentTime = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day,
                                                        evtStart.Hour, evtStart.Minute, evtStart.Second, DateTimeKind.Utc);
                    bool isDaylight = TimeZoneInfo.Local.IsDaylightSavingTime(currentTime.UTCToCourse(ActiveCourseUser.AbstractCourseID));

                    if (isDaylight)
                    {
                        evt.Start        = new iCalDateTime(evtStart.UTCToCourse(ActiveCourseUser.AbstractCourseID));
                        evt.End          = new iCalDateTime(evtEnd.UTCToCourse(ActiveCourseUser.AbstractCourseID));
                        evt.LastModified = new iCalDateTime(DateTime.Now);
                        evt.Summary      = cm.Name;
                        evt.Location     = cm.Location;
                        evt.RecurrenceRules.Add(pattern);
                    }
                    else //no longer DST
                    {
                        bool matchingStartDay = false;

                        /*
                         * if there happens to be a "meeting times" in the database without a day of the week associated with
                         * the meeting, we need to skip the while and switch case, otherwise it's an infinite loop!
                         */
                        bool meetingTimeWithoutDaysOfWeek = cm.Sunday || cm.Monday || cm.Tuesday || cm.Wednesday ||
                                                            cm.Thursday || cm.Friday || cm.Saturday ? false : true;

                        int count = 0; //infinite loop protection x2!

                        //WHILE matchingStartDay is false (default false) AND the meeting time has at least one day of the week
                        //AND if we've hit a count of 7, that means we've already checked each day of the week and will never find one!
                        //exit while if we fail either of these conditions!
                        while ((!matchingStartDay && !meetingTimeWithoutDaysOfWeek) && count < 7)
                        {
                            switch (currentTime.DayOfWeek) //find which day of the week for this meeting
                            {
                            case DayOfWeek.Monday:
                                if (cm.Monday)
                                {
                                    matchingStartDay = true;
                                }
                                break;

                            case DayOfWeek.Tuesday:
                                if (cm.Tuesday)
                                {
                                    matchingStartDay = true;
                                }
                                break;

                            case DayOfWeek.Wednesday:
                                if (cm.Wednesday)
                                {
                                    matchingStartDay = true;
                                }
                                break;

                            case DayOfWeek.Thursday:
                                if (cm.Thursday)
                                {
                                    matchingStartDay = true;
                                }
                                break;

                            case DayOfWeek.Friday:
                                if (cm.Friday)
                                {
                                    matchingStartDay = true;
                                }
                                break;

                            case DayOfWeek.Saturday:
                                if (cm.Saturday)
                                {
                                    matchingStartDay = true;
                                }
                                break;

                            case DayOfWeek.Sunday:
                                if (cm.Sunday)
                                {
                                    matchingStartDay = true;
                                }
                                break;

                            default:
                                matchingStartDay = false;
                                break;
                            }

                            if (!matchingStartDay)
                            {
                                currentTime = new DateTime(currentTime.Year, currentTime.Month, currentTime.AddDays(1).Day,
                                                           evtStart.Hour, evtStart.Minute, evtStart.Second, DateTimeKind.Utc);
                            }
                            count++; //infinite loop protection x2! if we've reached 7 we've cycled all weekdays, so get us out of here!
                        }

                        //proceed only if there was a day of the week found for this course meeting time
                        if (!meetingTimeWithoutDaysOfWeek && matchingStartDay)
                        {
                            evt.Start        = new iCalDateTime(currentTime.UTCToCourse(ActiveCourseUser.AbstractCourseID));
                            evt.End          = new iCalDateTime(evtEnd.UTCToCourse(ActiveCourseUser.AbstractCourseID));
                            evt.LastModified = new iCalDateTime(DateTime.Now);
                            evt.Summary      = cm.Name;
                            evt.Location     = cm.Location;
                            evt.RecurrenceRules.Add(pattern);
                        }
                    }
                }

                //create the course breaks
                foreach (CourseBreak cb in course.CourseBreaks)
                {
                    DDay.iCal.Event evt      = courseCalendar.Create <DDay.iCal.Event>();
                    DateTime        evtStart = cb.StartDate.Date;
                    DateTime        evtEnd   = cb.EndDate.Date.AddDays(1);

                    evt.Summary      = cb.Name;
                    evt.Start        = new iCalDateTime(evtStart);
                    evt.End          = new iCalDateTime(evtEnd);
                    evt.LastModified = new iCalDateTime(DateTime.Now);
                }
            }//end if

            //add all the events to the calendar
            foreach (var e in events)
            {
                DDay.iCal.Event evt = courseCalendar.Create <DDay.iCal.Event>();

                evt.Start = new iCalDateTime(e.StartDate.UTCToCourse(ActiveCourseUser.AbstractCourseID));
                if (e.EndDate == null)
                {
                    evt.End = new iCalDateTime(e.StartDate.UTCToCourse(ActiveCourseUser.AbstractCourseID));
                    evt.End.AddMinutes(1);
                }
                else
                {
                    evt.End = new iCalDateTime(((DateTime)e.EndDate).UTCToCourse(ActiveCourseUser.AbstractCourseID));
                }

                evt.Summary = e.Title;
                if (e.Description != null)
                {
                    evt.Description = e.Description;
                }
            }

            // Create a serialization context and serializer factory.
            // These will be used to build the serializer for our object.
            ISerializationContext ctx     = new SerializationContext();
            ISerializerFactory    factory = new DDay.iCal.Serialization.iCalendar.SerializerFactory();
            // Get a serializer for our object
            IStringSerializer serializer = factory.Build(courseCalendar.GetType(), ctx) as IStringSerializer;

            string output = serializer.SerializeToString(courseCalendar);
            var    bytes  = Encoding.UTF8.GetBytes(output);

            SaveCourseCalendar(bytes, course.ID);
        }