public iCalendarCollectionInstance(ObjectInstance prototype, iCalendarCollection iCalendarCollection)
            : this(prototype)
        {
            if (iCalendarCollection == null)
            {
                throw new ArgumentNullException("iCalendarCollection");
            }

            m_iCalendarCollection = iCalendarCollection;
        }
Пример #2
0
 /// <summary>
 /// Loads and parses the selected calendars.
 /// </summary>
 protected void LoadSelectedCalendars()
 {
     _Calendars = new iCalendarCollection();
     foreach (ListItem li in CalendarList.Items)
     {
         // Make sure the item is selected
         if (li.Selected)
         {
             // Load the calendar from the file system
             _Calendars.Add(iCalendar.LoadFromFile(Path.Combine(_CalendarAbsPath, li.Text + @".ics")));
         }
     }
 }
Пример #3
0
 /// <summary>
 /// Loads and parses the selected calendars.
 /// </summary>
 protected void LoadSelectedCalendars()
 {
     _Calendars = new iCalendarCollection();
     foreach (ListItem li in CalendarList.Items)
     {
         // Make sure the item is selected
         if (li.Selected)
         {
             // Load the calendar from the file system
             _Calendars.Add(iCalendar.LoadFromFile(Path.Combine(_CalendarAbsPath, li.Text + @".ics")));                
         }
     }
 }
Пример #4
0
        static Utility()
        {
            categoryId = new CategoryController().GetUnCategorizedCategory().Id;
            calendars  = new iCalendarCollection();

            object calendarFeeds = GraffitiContext.Current["calendarFeeds"];

            if (!String.IsNullOrEmpty(calendarFeeds as String))
            {
                string[] feeds = calendarFeeds.ToString().Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string feed in feeds)
                {
                    calendars.AddRange(iCalendar.LoadFromUri(new Uri(feed)));
                }
            }
        }
Пример #5
0
        public void EVALUATION1()
        {
            iCalendarCollection calendars = new iCalendarCollection();
            calendars.Add(iCalendar.LoadFromFile(@"Calendars\Recurrence\RRULE21.ics"));
            calendars.Add(iCalendar.LoadFromFile(@"Calendars\Recurrence\RRULE22.ics"));

            Date_Time startDate = new Date_Time(1996, 1, 1, tzid, calendars[0]);
            Date_Time endDate = new Date_Time(1998, 4, 1, tzid, calendars[0]);
            
            List<Date_Time> DateTimes = new List<Date_Time>(new Date_Time[]
            {
                new Date_Time(1997, 9, 2, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1997, 9, 9, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1997, 9, 16, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1997, 9, 23, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1997, 9, 30, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1997, 11, 4, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1997, 11, 11, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1997, 11, 18, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1997, 11, 25, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1998, 1, 6, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1998, 1, 13, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1998, 1, 20, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1998, 1, 27, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1998, 3, 3, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1998, 3, 10, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1998, 3, 17, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1998, 3, 24, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1998, 3, 31, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1997, 9, 10, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1997, 9, 11, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1997, 9, 12, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1997, 9, 13, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1997, 9, 14, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1997, 9, 15, 9, 0, 0, tzid, calendars[0]),                
            });
            
            List<Event> occurrences = new List<Event>(calendars.GetRecurrencesForRange<Event>(startDate, endDate));
            foreach (Event evt in occurrences)
                Assert.IsTrue(DateTimes.Contains(evt.Start), "Event occurred on " + evt.Start + "; it should not have");
            foreach(Date_Time dt in DateTimes)
            {
                bool isFound = false;
                foreach (Event evt in occurrences)
                {
                    if (evt.Start.Equals(dt))
                    {
                        isFound = true;
                        break;
                    }
                }
                Assert.IsTrue(isFound, "Event should occur on " + dt);
            }
                    

            Assert.IsTrue(occurrences.Count == DateTimes.Count, "There should be exactly " + DateTimes.Count + " occurrences; there were " + occurrences.Count);
        }
Пример #6
0
        /// <summary>
        /// Creates the iCalendar object and populates it with events
        /// </summary>
        /// <param name="calendarProps">The calendar props.</param>
        /// <returns></returns>
        private iCalendar CreateICalendar(CalendarProps calendarProps)
        {
            // Get a list of Rock Calendar Events filtered by calendarProps
            List <EventItem> eventItems = GetEventItems(calendarProps);

            // Create the iCalendar
            iCalendar icalendar = new iCalendar();

            icalendar.AddLocalTimeZone();

            // Create each of the events for the calendar(s)
            foreach (EventItem eventItem in eventItems)
            {
                foreach (EventItemOccurrence occurrence in eventItem.EventItemOccurrences)
                {
                    if (occurrence.Schedule == null)
                    {
                        continue;
                    }

                    iCalendarSerializer serializer = new iCalendarSerializer();
                    iCalendarCollection ical       = (iCalendarCollection)serializer.Deserialize(occurrence.Schedule.iCalendarContent.ToStreamReader());

                    foreach (var icalEvent in ical[0].Events)
                    {
                        // We get all of the schedule info from Schedule.iCalendarContent
                        Event ievent = icalEvent.Copy <Event>();

                        ievent.Summary  = !string.IsNullOrEmpty(eventItem.Name) ? eventItem.Name : string.Empty;
                        ievent.Location = !string.IsNullOrEmpty(occurrence.Location) ? occurrence.Location : string.Empty;

                        ievent.DTStart.SetTimeZone(icalendar.TimeZones[0]);
                        ievent.DTEnd.SetTimeZone(icalendar.TimeZones[0]);

                        // Rock has more descriptions than iCal so lets concatenate them
                        string description = CreateEventDescription(eventItem, occurrence);

                        // Don't set the description prop for outlook to force it to use the X-ALT-DESC property which can have markup.
                        if (interactionDeviceType != "Outlook")
                        {
                            ievent.Description = description.ConvertBrToCrLf()
                                                 .Replace("</P>", "")
                                                 .Replace("</p>", "")
                                                 .Replace("<P>", Environment.NewLine)
                                                 .Replace("<p>", Environment.NewLine)
                                                 .Replace("&nbsp;", " ")
                                                 .SanitizeHtml();
                        }

                        // HTML version of the description for outlook
                        ievent.AddProperty("X-ALT-DESC;FMTTYPE=text/html", "<html>" + description + "</html>");

                        // classification: "PUBLIC", "PRIVATE", "CONFIDENTIAL"
                        ievent.Class = "PUBLIC";

                        if (!string.IsNullOrEmpty(eventItem.DetailsUrl))
                        {
                            Uri result;
                            if (Uri.TryCreate(eventItem.DetailsUrl, UriKind.Absolute, out result))
                            {
                                ievent.Url = result;
                            }
                            else if (Uri.TryCreate("http://" + eventItem.DetailsUrl, UriKind.Absolute, out result))
                            {
                                ievent.Url = result;
                            }
                        }

                        // add contact info if it exists
                        if (occurrence.ContactPersonAlias != null)
                        {
                            ievent.Organizer            = new Organizer(string.Format("MAILTO:{0}", occurrence.ContactPersonAlias.Person.Email));
                            ievent.Organizer.CommonName = occurrence.ContactPersonAlias.Person.FullName;

                            // Outlook doesn't seems to use Contacts or Comments
                            string contactName  = !string.IsNullOrEmpty(occurrence.ContactPersonAlias.Person.FullName) ? "Name: " + occurrence.ContactPersonAlias.Person.FullName : string.Empty;
                            string contactEmail = !string.IsNullOrEmpty(occurrence.ContactEmail) ? ", Email: " + occurrence.ContactEmail : string.Empty;
                            string contactPhone = !string.IsNullOrEmpty(occurrence.ContactPhone) ? ", Phone: " + occurrence.ContactPhone : string.Empty;
                            string contactInfo  = contactName + contactEmail + contactPhone;

                            ievent.Contacts.Add(contactInfo);
                            ievent.Comments.Add(contactInfo);
                        }

                        // TODO: categories - comma delimited list of whatever, might use audience
                        foreach (var a in eventItem.EventItemAudiences)
                        {
                            ievent.Categories.Add(a.DefinedValue.Value);
                        }

                        //// No attachments for now.
                        ////if ( eventItem.PhotoId != null )
                        ////{
                        ////    // The DDay Attachment obj doesn't allow you to name the attachment. Nice huh? So just add prop manually...
                        ////    ievent.AddProperty( "ATTACH;VALUE=BINARY;ENCODING=BASE64;X-FILENAME=\"" + eventItem.Photo.FileName + "\"", Convert.ToBase64String( eventItem.Photo.ContentStream.ReadBytesToEnd().ToArray() ) );
                        ////}

                        icalendar.Events.Add(ievent);
                    }
                }
            }

            return(icalendar);
        }
Пример #7
0
        /// <summary>
        /// Creates the iCalendar object and populates it with events
        /// </summary>
        /// <param name="calendarProps">The calendar props.</param>
        /// <returns></returns>
        private iCalendar CreateICalendar(CalendarProps calendarProps, string interactionDeviceType)
        {
            // Get a list of confirmed attendances filtered by calendarProps
            List <Attendance> attendances = GetAttendances(calendarProps);

            // Create the iCalendar
            iCalendar icalendar = new iCalendar();

            icalendar.AddLocalTimeZone();
            TimeSpan duration          = TimeSpan.MinValue;
            int      currentScheduleId = -1;

            // Create each of the attendances
            foreach (var attendance in attendances)
            {
                using (var rockContext = new RockContext())
                {
                    var attendanceOccurrenceService = new AttendanceOccurrenceService(rockContext);

                    var schedule = attendanceOccurrenceService
                                   .Queryable()
                                   .AsNoTracking()
                                   .Where(a => a.Id == attendance.OccurrenceId)
                                   .Select(a => a.Schedule)
                                   .FirstOrDefault();

                    string scheduleName = schedule.Name;

                    // TODO: Construct a description that includes the group leader contact info and the URL to the schedule toolbox.
                    string description = schedule.Description;

                    string locationName = attendanceOccurrenceService
                                          .Queryable()
                                          .AsNoTracking()
                                          .Where(a => a.Id == attendance.OccurrenceId)
                                          .Select(a => a.Location.Name)
                                          .FirstOrDefault() ?? string.Empty;

                    if (schedule.Id != currentScheduleId)
                    {
                        // We have to get the duration from Schedule.iCal for this attendance.
                        // Attendances are ordered by scheduleId so this only happens once for each unique schedule.
                        iCalendarSerializer serializer = new iCalendarSerializer();
                        iCalendarCollection ical       = ( iCalendarCollection )serializer.Deserialize(schedule.iCalendarContent.ToStreamReader());
                        duration          = ical[0].Events[0].Duration;
                        currentScheduleId = schedule.Id;
                    }

                    var iCalEvent = new DDay.iCal.Event();
                    iCalEvent.Summary  = scheduleName;
                    iCalEvent.Location = locationName;
                    iCalEvent.DTStart  = new DDay.iCal.iCalDateTime(attendance.StartDateTime);
                    iCalEvent.DTStart.SetTimeZone(icalendar.TimeZones[0]);
                    iCalEvent.Duration = duration;

                    // Don't set the description prop for outlook to force it to use the X-ALT-DESC property which can have markup.
                    if (interactionDeviceType != "Outlook")
                    {
                        iCalEvent.Description = description.ConvertBrToCrLf().SanitizeHtml();
                    }

                    // HTML version of the description for outlook
                    iCalEvent.AddProperty("X-ALT-DESC;FMTTYPE=text/html", "<html>" + description + "</html>");

                    // classification: "PUBLIC", "PRIVATE", "CONFIDENTIAL"
                    iCalEvent.Class = "PUBLIC";

                    //Add contact info for the group leader
                    int groupId = attendanceOccurrenceService
                                  .Queryable()
                                  .AsNoTracking()
                                  .Where(a => a.Id == attendance.OccurrenceId)
                                  .Select(a => a.GroupId)
                                  .FirstOrDefault() ?? -1;

                    Person groupLeader = new GroupMemberService(rockContext).GetLeaders(groupId).AsNoTracking().Select(m => m.Person).FirstOrDefault() ?? null;

                    if (groupLeader != null)
                    {
                        iCalEvent.Organizer            = new Organizer(string.Format("MAILTO:{0}", groupLeader.Email));
                        iCalEvent.Organizer.CommonName = groupLeader.FullName;

                        // Outlook doesn't seem to use Contacts or Comments
                        string contactName  = !string.IsNullOrEmpty(groupLeader.FullName) ? "Name: " + groupLeader.FullName : string.Empty;
                        string contactEmail = !string.IsNullOrEmpty(groupLeader.Email) ? ", Email: " + groupLeader.Email : string.Empty;
                        string contactInfo  = contactName + contactEmail;

                        iCalEvent.Contacts.Add(contactInfo);
                        iCalEvent.Comments.Add(contactInfo);
                    }

                    icalendar.Events.Add(iCalEvent);
                }
            }

            return(icalendar);
        }
Пример #8
0
        static void Main(string[] args)
        {
            // Create an empty list of iCalendars
            iCalendarCollection iCalendars = new iCalendarCollection();

            // First, load the example iCalendar file normally
            iCalendars.Add(iCalendar.LoadFromFile(@"Example3.ics"));
            
            // Next, load the example iCalendar file into our CustomICalendar object,
            // so we can show the difference between loading it normally and loading
            // it into a custom object.
            iCalendars.Add(iCalendar.LoadFromFile<CustomICalendar>(@"Example3.ics"));

            // Since our CustomICalendar objects has its ComponentBaseTypeAttribute set
            // to our CustomComponentBase class, all of our objects are created with it.
            //
            // Hence, each of our events will not be loaded as Event objects, because we
            // instructed our CustomComponentBase class to create a CustomEvent class
            // whenever a VEVENT object was encountered.

            foreach (iCalendar iCal in iCalendars)
            {
                Console.WriteLine("iCalendar is of type: " + iCal.GetType().Name);

                int i = 1;

                //
                // Iterate through each unique component in the iCalendar
                //
                foreach (ComponentBase component in iCal.UniqueComponents)
                {
                    // Display the component's type                    
                    Console.WriteLine(i + ": Component is a " + component.GetType().Name + ", which is a subclass of " + component.GetType().BaseType.Name);
                    
                    if (component is CustomEvent)
                    {
                        // The component was loaded as a CustomEvent                        
                        CustomEvent evt = (CustomEvent)component;
      
                        // So, let's set some additional information
                        evt.AdditionalInformation = @"
More information to set about this event...
Note that this information will not be saved
when the iCalendar is serialized.  We'll deal
with this in the next example.
";

                        // Let's show its summary also...
                        Console.WriteLine("\tEvent summary: " + evt.Summary);
                    }
                    else
                    {
                        // The component is not a CustomEvent, because
                        // the iCalendar was loaded normally.
                        Console.WriteLine("\tComponent is not a CustomEvent.");
                    }

                    i++;
                }

                Console.WriteLine(Environment.NewLine);
            }
        }
Пример #9
0
	public IICalendarCollection  icalendar(
		ISerializationContext ctx
	) //throws RecognitionException, TokenStreamException
{
		IICalendarCollection iCalendars = new iCalendarCollection();
		
		
		
			SerializationUtil.OnDeserializing(iCalendars);
		
			IICalendar iCal = null;
			ISerializationSettings settings = ctx.GetService(typeof(ISerializationSettings)) as ISerializationSettings;
		
		{    // ( ... )*
			for (;;)
			{
				if ((LA(1)==CRLF||LA(1)==BEGIN))
				{
					{    // ( ... )*
						for (;;)
						{
							if ((LA(1)==CRLF))
							{
								match(CRLF);
							}
							else
							{
								goto _loop4_breakloop;
							}
							
						}
_loop4_breakloop:						;
					}    // ( ... )*
					match(BEGIN);
					match(COLON);
					match(VCALENDAR);
					{    // ( ... )*
						for (;;)
						{
							if ((LA(1)==CRLF))
							{
								match(CRLF);
							}
							else
							{
								goto _loop6_breakloop;
							}
							
						}
_loop6_breakloop:						;
					}    // ( ... )*
								
								ISerializationProcessor<IICalendar> processor = ctx.GetService(typeof(ISerializationProcessor<IICalendar>)) as ISerializationProcessor<IICalendar>;
								
								// Do some pre-processing on the calendar:
								if (processor != null)
									processor.PreDeserialization(iCal);
							
								iCal = (IICalendar)SerializationUtil.GetUninitializedObject(settings.iCalendarType);			
								SerializationUtil.OnDeserializing(iCal);
								
								// Push the iCalendar onto the serialization context stack
								ctx.Push(iCal);
							
					icalbody(ctx, iCal);
					match(END);
					match(COLON);
					match(VCALENDAR);
					{    // ( ... )*
						for (;;)
						{
							if ((LA(1)==CRLF) && (LA(2)==EOF||LA(2)==CRLF||LA(2)==BEGIN) && (tokenSet_0_.member(LA(3))))
							{
								match(CRLF);
							}
							else
							{
								goto _loop8_breakloop;
							}
							
						}
_loop8_breakloop:						;
					}    // ( ... )*
					
								// Do some final processing on the calendar:
								if (processor != null)
									processor.PostDeserialization(iCal);
							
								// Notify that the iCalendar has been loaded
								iCal.OnLoaded();
								iCalendars.Add(iCal);
								
								SerializationUtil.OnDeserialized(iCal);
								
								// Pop the iCalendar off the serialization context stack
								ctx.Pop();
							
				}
				else
				{
					goto _loop9_breakloop;
				}
				
			}
_loop9_breakloop:			;
		}    // ( ... )*
		
				SerializationUtil.OnDeserialized(iCalendars);
			
		return iCalendars;
	}
Пример #10
0
        static void Main(string[] args)
        {
            // Create an empty list of iCalendars
            iCalendarCollection iCalendars = new iCalendarCollection();

            // First, load the example iCalendar file normally
            iCalendars.Add(iCalendar.LoadFromFile(@"Example3.ics"));

            // Next, load the example iCalendar file into our CustomICalendar object,
            // so we can show the difference between loading it normally and loading
            // it into a custom object.
            iCalendars.Add(iCalendar.LoadFromFile <CustomICalendar>(@"Example3.ics"));

            // Since our CustomICalendar objects has its ComponentBaseTypeAttribute set
            // to our CustomComponentBase class, all of our objects are created with it.
            //
            // Hence, each of our events will not be loaded as Event objects, because we
            // instructed our CustomComponentBase class to create a CustomEvent class
            // whenever a VEVENT object was encountered.

            foreach (iCalendar iCal in iCalendars)
            {
                Console.WriteLine("iCalendar is of type: " + iCal.GetType().Name);

                int i = 1;

                //
                // Iterate through each unique component in the iCalendar
                //
                foreach (ComponentBase component in iCal.UniqueComponents)
                {
                    // Display the component's type
                    Console.WriteLine(i + ": Component is a " + component.GetType().Name + ", which is a subclass of " + component.GetType().BaseType.Name);

                    if (component is CustomEvent)
                    {
                        // The component was loaded as a CustomEvent
                        CustomEvent evt = (CustomEvent)component;

                        // So, let's set some additional information
                        evt.AdditionalInformation = @"
More information to set about this event...
Note that this information will not be saved
when the iCalendar is serialized.  We'll deal
with this in the next example.
";

                        // Let's show its summary also...
                        Console.WriteLine("\tEvent summary: " + evt.Summary);
                    }
                    else
                    {
                        // The component is not a CustomEvent, because
                        // the iCalendar was loaded normally.
                        Console.WriteLine("\tComponent is not a CustomEvent.");
                    }

                    i++;
                }

                Console.WriteLine(Environment.NewLine);
            }
        }
Пример #11
0
        public void EVALUATION1()
        {
            iCalendarCollection calendars = new iCalendarCollection();

            calendars.Add(iCalendar.LoadFromFile(@"Calendars\Recurrence\RRULE21.ics"));
            calendars.Add(iCalendar.LoadFromFile(@"Calendars\Recurrence\RRULE22.ics"));

            Date_Time startDate = new Date_Time(1996, 1, 1, tzid, calendars[0]);
            Date_Time endDate   = new Date_Time(1998, 4, 1, tzid, calendars[0]);

            List <Date_Time> DateTimes = new List <Date_Time>(new Date_Time[]
            {
                new Date_Time(1997, 9, 2, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1997, 9, 9, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1997, 9, 16, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1997, 9, 23, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1997, 9, 30, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1997, 11, 4, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1997, 11, 11, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1997, 11, 18, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1997, 11, 25, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1998, 1, 6, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1998, 1, 13, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1998, 1, 20, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1998, 1, 27, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1998, 3, 3, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1998, 3, 10, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1998, 3, 17, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1998, 3, 24, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1998, 3, 31, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1997, 9, 10, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1997, 9, 11, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1997, 9, 12, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1997, 9, 13, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1997, 9, 14, 9, 0, 0, tzid, calendars[0]),
                new Date_Time(1997, 9, 15, 9, 0, 0, tzid, calendars[0]),
            });

            List <Event> occurrences = new List <Event>(calendars.GetRecurrencesForRange <Event>(startDate, endDate));

            foreach (Event evt in occurrences)
            {
                Assert.IsTrue(DateTimes.Contains(evt.Start), "Event occurred on " + evt.Start + "; it should not have");
            }
            foreach (Date_Time dt in DateTimes)
            {
                bool isFound = false;
                foreach (Event evt in occurrences)
                {
                    if (evt.Start.Equals(dt))
                    {
                        isFound = true;
                        break;
                    }
                }
                Assert.IsTrue(isFound, "Event should occur on " + dt);
            }


            Assert.IsTrue(occurrences.Count == DateTimes.Count, "There should be exactly " + DateTimes.Count + " occurrences; there were " + occurrences.Count);
        }
Пример #12
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);
        }
Пример #13
0
        /// <summary>
        /// Get scheduled events into calendar
        /// </summary>
        /// <returns>Formatted Json events</returns>
        public JsonResult GetEvents( DateTime start, DateTime end,int id = 0)
        {
            IEnumerable<GroupInstance> groupInstances;
            if (id > 0)
            {
                var filteredGroups  =db.GroupInstances.Include(e => e.Group)
                                                  .Include(e => e.Group.Users)
                                                  .ToList()
                                                  .Where(x => x.Group.Users.Where(y => y.UserId == id
                                                       &&(((x.StartDateTime>=start
                                                           ||x.EndDateTime<=end)
                                                       &&x.RecurrenceRule==null)
                                                      ||x.RecurrenceRule!=null)).Any());
                groupInstances = filteredGroups;
            }
            else
            {
                groupInstances = db.GroupInstances.Include(e => e.Group)
                    .Include(e=>e.Group.Users).Where(x=>((x.StartDateTime>=start ||x.EndDateTime<=end)&&x.RecurrenceRule==null)||x.RecurrenceRule!=null).ToList();
            }
            if (groupInstances.Any())
            {
                var recurrence = groupInstances.Where(x => !String.IsNullOrWhiteSpace(x.RecurrenceRule)).FirstOrDefault();
                var list = new List<dynamic>();
                foreach (var instance in groupInstances)
                {
                    if (!String.IsNullOrWhiteSpace(instance.RecurrenceRule))
                    {
                        iCalendarSerializer serializer = new iCalendarSerializer();
                        iCalendarCollection ical = new iCalendarCollection();
                        using (TextReader tr = new StringReader(instance.RecurrenceRule))
                        {
                            ical = (iCalendarCollection)serializer.Deserialize(tr);
                        }

                            Event ev = new Event();
                            if (ical.Count == 0)
                            {
                                RecurrencePattern rp = new RecurrencePattern(instance.RecurrenceRule);
                                ev.RecurrenceRules.Add(rp);
                            }
                            else
                            {
                                ev = (Event)ical.First().Events.First();
                            }
                            var ex = ev.ExceptionDates;
                        ev.Start = new iCalDateTime(instance.StartDateTime);
                        var occ = ev.GetOccurrences(start.AddDays(-1), end);
                        if (occ != null)
                        {
                            foreach (var occurence in occ)
                            {
                                    var user = instance.Group.Users.FirstOrDefault(y => Roles.IsUserInRole(y.UserName, "Teacher"));
                                    var color = "#FFFFFF";
                                    if (user != null)
                                    {
                                        color = user.HexColor;
                                    }
                                    list.Add(new
                                    {
                                        title = instance.Group.Name,
                                        start = CreateNewDateTime(occurence.Period.StartTime, instance.StartDateTime).ToString("s"),
                                        end = CreateNewDateTime(occurence.Period.EndTime, instance.EndDateTime).ToString("s"),
                                        editable = false,
                                        GroupInstanceId = instance.GroupInstanceId,
                                        ClassroomId = instance.ClassroomId,
                                        GroupId = instance.GroupId,
                                        Color = color,
                                        RecurrenceRule = recurrence.RecurrenceRule
                                    });
                            }
                        }
                    }
                    else
                    {
                        list.Add(new
                         {
                             title = instance.Group.Name,
                             start = instance.StartDateTime.ToString("s"),
                             end = instance.EndDateTime.ToString("s"),
                             editable = false,
                             GroupInstanceId = instance.GroupInstanceId,
                             ClassroomId = instance.ClassroomId,
                             GroupId = instance.GroupId,
                             Color = instance.Group.Users.FirstOrDefault(y => Roles.IsUserInRole(y.UserName, "Teacher")).HexColor
                         });

                    }
                }
                return Json(list, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(null, JsonRequestBehavior.AllowGet);
            }
        }