Exemple #1
1
        static void Main(string[] args)
        {
            // Create a new calendar
            IICalendar iCal = new iCalendar();

            // Add the local time zone to the calendar
            ITimeZone local = iCal.AddLocalTimeZone();

            // Build a list of additional time zones
            // from .NET Framework.
            List<ITimeZone> otherTimeZones = new List<ITimeZone>();                        
            foreach (TimeZoneInfo tzi in System.TimeZoneInfo.GetSystemTimeZones())
            {
                // We've already added the local time zone, so let's skip it!
                if (tzi != System.TimeZoneInfo.Local)
                {
                    // Add the time zone to our list (but don't include it directly in the calendar).
                    otherTimeZones.Add(iCalTimeZone.FromSystemTimeZone(tzi));
                }
            }

            // Create a new event in the calendar
            // that uses our local time zone
            IEvent evt = iCal.Create<Event>();
            evt.Summary = "Test Event";
            evt.Start = iCalDateTime.Today.AddHours(8).SetTimeZone(local);            
            evt.Duration = TimeSpan.FromHours(1);

            // Get all occurrences of the event that happen today
            foreach (Occurrence occurrence in iCal.GetOccurrences<IEvent>(iCalDateTime.Today))
            {
                // Write the event with the time zone information attached
                Console.WriteLine(occurrence.Period.StartTime);

                // Note that the time printed is identical to the above, but without time zone information.
                Console.WriteLine(occurrence.Period.StartTime.Local);

                // Convert the start time to other time zones and display the relative time.
                foreach (ITimeZone otherTimeZone in otherTimeZones)
                    Console.WriteLine(occurrence.Period.StartTime.ToTimeZone(otherTimeZone));
            }
        }
Exemple #2
0
        public ActionResult Calendar()
        {
            DDay.iCal.iCalendar iCal = new DDay.iCal.iCalendar();

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

            // Set information about the event
            evt.Start       = iCalDateTime.Today.AddHours(8);
            evt.End         = evt.Start.AddHours(18); // This also sets the duration
            evt.Description = "The event description";
            evt.Location    = "Event location";
            evt.Summary     = "18 hour event summary";

            // Set information about the second event
            evt          = iCal.Create <Event>();
            evt.Start    = iCalDateTime.Today.AddDays(5);
            evt.End      = evt.Start.AddDays(1);
            evt.IsAllDay = true;
            evt.Summary  = "All-day 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, "calendar.ics"));
        }
        // GET: Calendar
        public ActionResult Index()
        {
            foreach (var r in Request.Params.AllKeys)
            {
                System.Diagnostics.Debug.WriteLine(r + " = " + Request.Params[r]);
            }

            var iCal = new iCalendar();

            Event evt = iCal.Create<Event>();
            evt.Start = iCalDateTime.Today.AddHours(8);
            evt.End = evt.Start.AddHours(18); // This also sets the duration
            evt.Description = "The event description";
            evt.Location = "Event location";
            evt.Summary = "18 hour event summary";
            
            evt = iCal.Create<Event>();
            evt.Start = iCalDateTime.Today.AddDays(5);
            evt.End = evt.Start.AddDays(1);
            evt.IsAllDay = true;
            evt.Summary = "All-day event";

            ISerializationContext ctx = new SerializationContext();
            ISerializerFactory factory = new DDay.iCal.Serialization.iCalendar.SerializerFactory();
            IStringSerializer serializer = factory.Build(iCal.GetType(), ctx) as IStringSerializer;

            string output = serializer.SerializeToString(iCal);
            var bytes = System.Text.Encoding.UTF8.GetBytes(output);

            return File(bytes, "text/calendar");
        }
        public void ExportSolution()
        {
            DDay.iCal.iCalendar iCal = new DDay.iCal.iCalendar();
            var t = new DBManager();
            t.initInputData();
            t.initOutputData();
            foreach(ScheduledTimeSlot[] solution in (t.solutions))
            {
                for (int i = 0; i < solution.Length; i++)
                {
                    Event evt = iCal.Create<Event>();

                    evt.Start = iCalDateTime.Today.AddHours((int)solution[i].timeSlot.StartHour).AddDays((int)(solution[i].timeSlot.Day));

                    evt.End = iCalDateTime.Today.AddHours((int)solution[i].timeSlot.EndHour).AddDays((int)(solution[i].timeSlot.Day));

                    evt.Summary = string.Join(", ", solution[i].groups.Select(g => g.name));

                    evt.Location = solution[i].room.nameOrNumber;
                }
                break;
            }

            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 bytes = Encoding.UTF8.GetBytes(output);

            File.WriteAllBytes("solution.ics", bytes);
        }
Exemple #5
0
        private System.IO.MemoryStream Generacion(string Titulo, String nombreCalendario, DateTime fechayHoraInicio, Int32 duracionEnMinutos, string ubicacion)
        {
            DDay.iCal.iCalendar iCal = new DDay.iCal.iCalendar();
            // Create the event, and add it to the iCalendar
            Event evt = iCal.Create <Event>();

            // Set information about the event
            evt.Start       = new iCalDateTime(fechayHoraInicio);
            evt.End         = evt.Start.AddMinutes(duracionEnMinutos); // This also sets the duration
            evt.Description = String.Format("Agenda del día {0} a las {1}",
                                            fechayHoraInicio.ToString("dd 'de' MMM 'de' yyyy"),
                                            fechayHoraInicio.ToString("HH:MM")
                                            );
            evt.Location = ubicacion;
            evt.Summary  = Titulo;
            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 bytes = Encoding.UTF8.GetBytes(output);

            //return File(bytes, contentType, DownloadFileName);
            System.IO.MemoryStream data = new System.IO.MemoryStream(bytes);
            return(data);
        }
Exemple #6
0
        public void CreateEntry(string summary, DateTime date, string icsFilename) {
            var ical = new iCalendar();
            var ev = ical.Create<Event>();
            ev.Summary = summary;
            ev.Start = new iCalDateTime(date);

            SaveToFile(icsFilename, ical);
        }
Exemple #7
0
        private Response GetCalendarFeed()
        {
            var pastDays = 7;
            var futureDays = 28;            
            var start = DateTime.Today.AddDays(-pastDays);
            var end = DateTime.Today.AddDays(futureDays);

            // TODO: Remove start/end parameters in v3, they don't work well for iCal
            var queryStart = Request.Query.Start;
            var queryEnd = Request.Query.End;
            var queryPastDays = Request.Query.PastDays;
            var queryFutureDays = Request.Query.FutureDays;

            if (queryStart.HasValue) start = DateTime.Parse(queryStart.Value);
            if (queryEnd.HasValue) end = DateTime.Parse(queryEnd.Value);

            if (queryPastDays.HasValue)
            {
                pastDays = int.Parse(queryPastDays.Value);
                start = DateTime.Today.AddDays(-pastDays);
            }

            if (queryFutureDays.HasValue)
            {
                futureDays = int.Parse(queryFutureDays.Value);
                end = DateTime.Today.AddDays(futureDays);
            }

            var episodes = _episodeService.EpisodesBetweenDates(start, end, false);
            var icalCalendar = new iCalendar();

            foreach (var episode in episodes.OrderBy(v => v.AirDateUtc.Value))
            {
                var occurrence = icalCalendar.Create<Event>();
                occurrence.UID = "NzbDrone_episode_" + episode.Id.ToString();
                occurrence.Status = episode.HasFile ? EventStatus.Confirmed : EventStatus.Tentative;
                occurrence.Start = new iCalDateTime(episode.AirDateUtc.Value) { HasTime = true };
                occurrence.End = new iCalDateTime(episode.AirDateUtc.Value.AddMinutes(episode.Series.Runtime)) { HasTime = true };
                occurrence.Description = episode.Overview;
                occurrence.Categories = new List<string>() { episode.Series.Network };

                switch (episode.Series.SeriesType)
                {
                    case SeriesTypes.Daily:
                        occurrence.Summary = string.Format("{0} - {1}", episode.Series.Title, episode.Title);
                        break;

                    default:
                        occurrence.Summary = string.Format("{0} - {1}x{2:00} - {3}", episode.Series.Title, episode.SeasonNumber, episode.EpisodeNumber, episode.Title);
                        break;
                }
            }

            var serializer = new DDay.iCal.Serialization.iCalendar.SerializerFactory().Build(icalCalendar.GetType(), new DDay.iCal.Serialization.SerializationContext()) as DDay.iCal.Serialization.IStringSerializer;
            var icalendar = serializer.SerializeToString(icalCalendar);

            return new TextResponse(icalendar, "text/calendar");
        }
Exemple #8
0
        public void CreateEntry(string summary, string description, DateTime start, DateTime end, string icsFilename) {
            var ical = new iCalendar();
            var ev = ical.Create<Event>();
            ev.Summary = summary;
            ev.Description = description;
            ev.Start = new iCalDateTime(start);
            ev.End = new iCalDateTime(end);

            SaveToFile(icsFilename, ical);
        }
Exemple #9
0
        /// <summary>
        /// The main program execution.
        /// </summary>
        static void Main(string[] args)
        {
            // Create a new iCalendar
            iCalendar iCal = new iCalendar();
            
            // Create the event, and add it to the iCalendar
            Event evt = iCal.Create<Event>();

            // Set information about the event
            evt.Start = iCalDateTime.Today.AddHours(8);            
            evt.End = evt.Start.AddHours(18); // This also sets the duration
            evt.Description = "The event description";
            evt.Location = "Event location";
            evt.Summary = "18 hour event summary";

            // Set information about the second event
            evt = iCal.Create<Event>();
            evt.Start = iCalDateTime.Today.AddDays(5);
            evt.End = evt.Start.AddDays(1);
            evt.IsAllDay = true;
            evt.Summary = "All-day event";

            // Display each event
            foreach(Event e in iCal.Events)
                Console.WriteLine("Event created: " + GetDescription(e));
            
            // Serialize (save) the iCalendar
            iCalendarSerializer serializer = new iCalendarSerializer();
            serializer.Serialize(iCal, @"iCalendar.ics");
            Console.WriteLine("iCalendar file saved." + Environment.NewLine);
            
            // Load the calendar from the file we just saved
            IICalendarCollection calendars = iCalendar.LoadFromFile(@"iCalendar.ics");
            Console.WriteLine("iCalendar file loaded.");

            // Iterate through each event to display its description
            // (and verify the file saved correctly)
            foreach (IICalendar calendar in calendars)
            {
                foreach (IEvent e in calendar.Events)
                    Console.WriteLine("Event loaded: " + GetDescription(e));
            }
        }
Exemple #10
0
        /// <summary>
        /// Appends the episode to an iCalendar calendar
        /// </summary>
        /// <param name="ical">The iCalendar to append to</param>
        public void CreateEventFromEpisode(iCalendar ical, int offset)
        {
            Event e = ical.Create<Event>();

            iCalDateTime offsetDate = (iCalDateTime)date.AddHours(offset);

            e.Start = offsetDate;
            e.End = offsetDate.AddHours(1);
            e.Summary = seriesTitle;
            e.Description = episodeTitle;
        }
 public static Event DinnerToEvent(Dinner dinner, iCalendar iCal)
 {
     string eventLink = "http://nrddnr.com/" + dinner.DinnerID;
     Event evt = iCal.Create<Event>();
     evt.Start = dinner.EventDate;
     evt.Duration = new TimeSpan(3, 0, 0);
     evt.Location = dinner.Address;
     evt.Summary = String.Format("{0} with {1}", dinner.Description, dinner.HostedBy);
     evt.AddContact(dinner.ContactPhone);
     evt.Geo = new Geo(dinner.Latitude, dinner.Longitude);
     evt.Url = eventLink;
     evt.Description = eventLink;
     return evt;
 }
    public ActionResult TeamFeed(int seasonId, int teamId, string desc)
    {

      var seasonName = _context.Seasons.Where(x => x.SeasonId == seasonId).Single().SeasonName;
      var teamName = _context.Teams.Where(x => x.TeamId == teamId).Single().TeamNameLong;

      List<GameTeam> gameTeams = _context.GameTeams
                              .IncludeAll()
                              .Where(x => x.SeasonId == seasonId && x.TeamId == teamId)
                              .ToList();

      iCalendar ical = new iCalendar();
      ical.Properties.Set("X-WR-CALNAME", "LO30Schedule-" + teamName.Replace(" ", "") + "-" + seasonName.Replace(" ", ""));
      foreach (var gameTeam in gameTeams)
      {
        Event icalEvent = ical.Create<Event>();

        var summary = gameTeam.OpponentTeam.TeamNameShort + " vs " + gameTeam.Team.TeamNameShort;
        if (gameTeam.HomeTeam)
        {
          summary = gameTeam.Team.TeamNameShort + " vs " + gameTeam.OpponentTeam.TeamNameShort;
        }

        icalEvent.Summary = summary;
        icalEvent.Description = summary + " " + gameTeam.Game.Location;

        var year = gameTeam.Game.GameDateTime.Year;
        var mon = gameTeam.Game.GameDateTime.Month;
        var day = gameTeam.Game.GameDateTime.Day;
        var hr = gameTeam.Game.GameDateTime.Hour;
        var min = gameTeam.Game.GameDateTime.Minute;
        var sec = gameTeam.Game.GameDateTime.Second;
        icalEvent.Start = new iCalDateTime(gameTeam.Game.GameDateTime);
        icalEvent.Duration = TimeSpan.FromHours(1.25);
        //icalEvent.Location = "Eddie Edgar " + gameTeam.Game.Location;  // TODO set the Rink location
        icalEvent.Location = "Eddie Edgar";
      }

      ISerializationContext ctx = new SerializationContext();
      ISerializerFactory factory = new SerializerFactory();
      IStringSerializer serializer = factory.Build(ical.GetType(), ctx) as IStringSerializer;

      string output = serializer.SerializeToString(ical);
      var contentType = "text/calendar";

      return Content(output, contentType);
    }
        // From: http://sourcefield.blogspot.com/2011/06/dday-ical-example.html
        public void Example()
        {
            // #1: Monthly meetings that occur on the last Wednesday from 6pm - 7pm

            // Create an iCalendar
            var iCal = new iCalendar();

            // Create the event
            var evt = iCal.Create<Event>();
            evt.Summary = "Test Event";
            evt.Start = new iCalDateTime(2008, 1, 1, 18, 0, 0); // Starts January 1, 2008 @ 6:00 P.M.
            evt.Duration = TimeSpan.FromHours(1);

            // Add a recurrence pattern to the event
            var rp = new RecurrencePattern {Frequency = FrequencyType.Monthly};
            rp.ByDay.Add(new WeekDay(DayOfWeek.Wednesday, FrequencyOccurrence.Last));
            evt.RecurrenceRules.Add(rp);

            // #2: Yearly events like holidays that occur on the same day each year.
            // The same as #1, except:
            var rp2 = new RecurrencePattern {Frequency = FrequencyType.Yearly};
            evt.RecurrenceRules.Add(rp2);

            // #3: Yearly events like holidays that occur on a specific day like the first monday.
            // The same as #1, except:
            var rp3 = new RecurrencePattern {Frequency = FrequencyType.Yearly};
            rp3.ByMonth.Add(3);
            rp3.ByDay.Add(new WeekDay(DayOfWeek.Monday, FrequencyOccurrence.First));
            evt.RecurrenceRules.Add(rp3);

            /*
            Note that all events occur on their start time, no matter their
            recurrence pattern. So, for example, you could occur on the first Monday
            of every month, but if your event is scheduled for a Friday (i.e.
            evt.Start = new iCalDateTime(2008, 3, 7, 18, 0, 0)), then it will first
            occur on that Friday, and then the first Monday of every month after
            that.

             this can be worked around by doing this:
             IPeriod nextOccurrence = pattern.GetNextOccurrence(dt);
             evt.Start = nextOccurrence.StartTime;
             */
        }
        public ActionResult ExportSolution()
        {
            var userDetail = SessionHelper.GetUserDetailFromSession();

            if (userDetail == null)
            {
                return(RedirectToAction("Index", "Login", new { ReturnUrl = "/BookRoom" }));
            }
            int UserId         = Convert.ToInt32(userDetail.user.id);
            var calendarevents = db.BookRooms.Where(x => x.UserId == UserId && x.IsSyncIcal == false && x.IsActive == true).ToList();
            // var calendarevents = CM.calendardetailtomodel();
            var FileTime = DateTime.Now.ToFileTime();
            var ext      = ".ics";

            DDay.iCal.iCalendar iCal = new DDay.iCal.iCalendar();
            foreach (var demoEvent in calendarevents)
            {
                Event evt = iCal.Create <Event>();
                evt.Start       = new iCalDateTime(demoEvent.StartDate);
                evt.End         = new iCalDateTime(demoEvent.EndDate);
                evt.Description = demoEvent.Description;
                evt.Summary     = demoEvent.Description;
                var datas = db.BookRooms.Where(x => x.BookRoomId == demoEvent.BookRoomId).FirstOrDefault();
                if (datas != null)
                {
                    datas.IsSyncIcal = true;
                    db.SaveChanges();//update
                    //TempData["StatusMsg"] = "Success";
                }
            }
            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, FileTime + ext));
        }
        protected override void WriteFile(System.Web.HttpResponseBase response)
        {
            iCalendar iCal = new iCalendar();

            var evnt = iCal.Create<Event>();

            evnt.Summary = _info.Name;
            evnt.Start = new iCalDateTime(_info.StartDate);
            evnt.Duration = _info.Duration;
            evnt.GeographicLocation = _info.Geo;
            evnt.Location = _info.Location;
            evnt.Url = new Uri(_info.Url);

            //iCal.Events.Add(evnt);

            var ser = new iCalendarSerializer();
            string result = ser.SerializeToString(iCal);
            //iCalendarSerializer serializer = new iCalendarSerializer(iCal);
            //string result = serializer.SerializeToString();
            response.ContentEncoding = Encoding.UTF8;
            response.Write(result);
        }
        /// <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 { }
            }
        }
        //[ChildActionOnly]
        //public ActionResult GetEventDetails(int id, int calendar, int type = 0)
        //{
        //    //EventLocation l = null;
        //    string evm = null;
        //    //var ms = Services.MemberService;
        //    //if (type == 0)
        //    //{
        //    //    evm = EventService.GetEventDetails(id);
        //    //}
        //    //else if (type == 1)
        //    //{
        //    //    evm = RecurringEventService.GetEventDetails(id);
        //    //}
        //    return PartialView("EventDetails", evm);
        //}
        public string GetIcsForCalendar(int id)
        {
            {
                // mandatory for outlook 2007
                //if (String.IsNullOrEmpty(organizer))
                //    throw new Exception("Organizer provided was null");

                var iCal = new iCalendar
                {
                    Method = "REQUEST",
                    //Method = "PUBLISH",
                    Version = "2.0"
                };

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

                var cs = ApplicationContext.Current.Services.ContentService;
                var content = cs.GetById(id);

                var start = Convert.ToDateTime(content.GetValue("start").ToString());
                var end = Convert.ToDateTime(content.GetValue("end").ToString());
                evt.Start = new iCalDateTime(start.ToUniversalTime());
                evt.End = new iCalDateTime(end.ToUniversalTime());

                evt.Summary = content.Name.ToCleanString(CleanStringType.FileName); ;
                TimeSpan ts = start.ToUniversalTime() - end.ToUniversalTime();
                evt.Duration = ts;
                evt.Description = content.GetValue("bodyText").ToString();
                evt.Location = "Uppsala";
                evt.IsAllDay = false;
                //evt.UID = String.IsNullOrEmpty(eventId) ? new Guid().ToString() : eventId;
                evt.UID = new Guid().ToString();
                evt.Organizer = new Organizer(ConfigurationManager.AppSettings["EventContact"]);
                evt.Alarms.Add(new Alarm
                {
                    Duration = new TimeSpan(0, 15, 0),
                    Trigger = new Trigger(new TimeSpan(0, 15, 0)),
                    Action = AlarmAction.Display,
                    Description = "Reminder"
                });
                return new iCalendarSerializer().SerializeToString(iCal);
                //ISerializationContext ctx = new SerializationContext();
                //ISerializerFactory factory = new SerializerFactory();
                //var serializer = factory.Build(iCal.GetType(), ctx) as IStringSerializer;
                //var output = serializer.SerializeToString(iCal);
                //var contentType = "text/calendar";
                //var bytes = Encoding.UTF8.GetBytes(output);

                //return File(bytes, contentType, eventName + ".ics");
            }
        }
        public ActionResult GetIcsForEvent(int id, int type = 0)
        {
            var iCal = new iCalendar();
            var evt = iCal.Create<Event>();

            var cs = ApplicationContext.Current.Services.ContentService;
            var content = cs.GetById(id);
            var seminarStart = Convert.ToDateTime(content.GetValue("start").ToString());
            var start = Convert.ToDateTime(content.GetValue("start").ToString());
            var end = Convert.ToDateTime(content.GetValue("end").ToString());
            evt.Start = new iCalDateTime(start.ToUniversalTime());
            evt.End = new iCalDateTime(end.ToUniversalTime());

            var eventName = evt.Name= content.Name.ToCleanString(CleanStringType.FileName);
            var f =VirtualPathUtility.ToAbsolute(Umbraco.Media(content.GetValue("seminarPoster").ToString()).umbracoFile);
            Attachment poster = new Attachment(f);
            evt.Attachments.Add(poster);

            var gmapLocation = content.GetValue<GMapsLocation>("location");
            var lat = gmapLocation.Lat;
            var lng = gmapLocation.Lng;
            evt.GeographicLocation = new GeographicLocation(Convert.ToDouble(lat), Convert.ToDouble(lng));
            ISerializationContext ctx = new SerializationContext();
            ISerializerFactory factory = new SerializerFactory();
            // Get a serializer for our object
            var serializer = factory.Build(iCal.GetType(), ctx) as IStringSerializer;

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

            return File(bytes, contentType, eventName + ".ics");

            //if (type == 0)
            //{
            //    //Fetch Event
            //    var ectrl = new EventApiController();
            //    var e = ectrl.GetById(id);

            //    if (e.End != null)
            //    {
            //        var end = (DateTime)e.End;

            //    }

            //    evt.IsAllDay = e.AllDay;

            //    //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;
            //    }

            //    var attendes = new List<IAttendee>();

            //    if (e.Organiser != null && e.Organiser != 0)
            //    {
            //        var ms = Services.MemberService;
            //        var member = ms.GetById(e.Organiser);
            //        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;
            //    }
            //}
            //else if (type == 1)
            //{
            //    var ectrl = new REventApiController();
            //    var e = ectrl.GetById(id);

            //    evt.Summary = e.Title;
            //    evt.IsAllDay = e.AllDay;

            //    //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;
            //    }

            //    RecurrencePattern rp = null;
            //    rp = new RecurrencePattern();
            //    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;
            //            }
            //    }
            //    rp.ByDay.AddRange(e.Days.Select(x => new WeekDay(x.ToString())));

            //    evt.RecurrenceRules.Add(rp);

            //    var tmp_event = new ScheduleWidget.ScheduledEvents.Event()
            //    {
            //        Title = e.Title,
            //        FrequencyTypeOptions = (FrequencyTypeEnum)e.Frequency
            //    };

            //    foreach (var day in e.Days)
            //    {
            //        tmp_event.DaysOfWeekOptions = tmp_event.DaysOfWeekOptions | (DayOfWeekEnum)day;
            //    }
            //    foreach (var i in e.MonthlyIntervals)
            //    {
            //        tmp_event.MonthlyIntervalOptions = tmp_event.MonthlyIntervalOptions | (MonthlyIntervalEnum)i;
            //    }

            //    Schedule schedule = new Schedule(tmp_event);

            //    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.Organiser != null && e.Organiser != 0)
            //    {
            //        var ms = Services.MemberService;
            //        var member = ms.GetById(e.Organiser);
            //        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.
        }
Exemple #19
0
    public string GetPubliekIcs()
    {
      iCalendar iCal = new iCalendar();

      foreach(var item in Items.Where(c => c.IsPublic))
      {
        Event evt = iCal.Create<Event>();
        evt.Start = item.When;
        evt.End = item.When.AddHours(1);
        evt.Summary = item.What;
        evt.Location = item.Where;
      }

      return new iCalendarSerializer().SerializeToString(iCal);
    }
Exemple #20
0
        /// <summary>
        /// Write out data in iCal format for consumption by calendar apps.
        /// </summary>
        private static void WritePerformancesIcal()
        {
            string tzid = iCalTimeZone.FromLocalTimeZone().TZID;

            // Write out a calendar of each individual performance.
            iCalendar performancesCalendar = new iCalendar();
            performancesCalendar.AddLocalTimeZone();

            foreach (Performance performance in _performances)
            {
                Event entry = performancesCalendar.Create<Event>();
                entry.DTStamp = new iCalDateTime(performance.StartTime);
                entry.UID = GetMD5Hash(string.Format("{0}{1}{2}", performance.StartTime.Ticks.ToString(), performance.Showcase.Name, performance.Artist.Name));
                entry.Start = new iCalDateTime(performance.StartTime, tzid);
                entry.End = new iCalDateTime(performance.EndTime, tzid);
                entry.IsAllDay = false;
                entry.Location = performance.Showcase.Venue;
                entry.Summary = performance.Artist.Name;
                entry.Description = string.Format(
                    "{0} ({1})\n{2}\n\n{3}\n{4}\n\nTickets\n{5}\n\nAll Ages? {6}\nIncluded in pass? {7}{8}",
                    performance.Artist.Name,
                    performance.PerformanceType,
                    performance.Artist.ArtistLink,
                    performance.Showcase.Name,
                    performance.Showcase.ShowcaseLink,
                    performance.Showcase.TicketLink,
                    performance.Showcase.IsAllAges ? "yes" : "no",
                    performance.Showcase.IsIncludedWithPass ? "yes" : "no",
                    performance.Showcase.SetTimesAreEstimated ? "\n\nWarning: Set times are estimated for this showcase and are almost certainly incorrect." : string.Empty);
            }

            new iCalendarSerializer().Serialize(performancesCalendar, Path.Combine(_dataDirectory, "performances.ics"));
        }
Exemple #21
0
        public static void Main(string[] args)
        {
            // Название нашей таблицы с расписанием.
            string filePath = @"test2.xlsx";

            // Парсим xlsx-таблицу
            List<WorkDay> week = ParseExcelSchedule.Parse(filePath);

            // Задаем дату начала семестра.
            iCalDateTime startStudy = new iCalDateTime(2015, 9, 1);

            // Создаём календарь, в который будем сохранять матчи.
            iCalendar CalForSchedule = new iCalendar
            {
                Method = "PUBLISH",
                Version = "2.0",
            };

            // Эти настройки нужны для календаря Mac, чтобы он был неотличим от
            // оригинального календаря (т.е. созданного внутри Mac Calendar)
            CalForSchedule.AddProperty("CALSCALE", "GREGORIAN");
            CalForSchedule.AddProperty("X-WR-CALNAME", "Расписание");
            CalForSchedule.AddProperty("X-WR-TIMEZONE", "Europe/Moscow");
            CalForSchedule.AddLocalTimeZone();

            // Сохраняем дату начала первой учебной недели.
            //TODO тут какое-то говно с преобразованием iCalDateTime в IDateTime
            int numberOfFirstDayOfFirstStudyWeek = startStudy.DayOfYear - ParseExcelSchedule.GetIntNumberFromDayWeek(startStudy.DayOfWeek.ToString());
            iCalDateTime firstDayOfFirstStudyWeek = new iCalDateTime(startStudy.FirstDayOfYear.AddDays(numberOfFirstDayOfFirstStudyWeek));

            // Пробегаемся по всем учебным дням в неделе.
            foreach (WorkDay workDay in week)
            {
                // Информация для отладки.
                Console.WriteLine(workDay);

                // Плюсуем к понедельнику первой учебной недели номер нашего обрабатываемого дня
                iCalDateTime tmpDate = new iCalDateTime(firstDayOfFirstStudyWeek.AddDays(workDay.dayNumber - 1));
                // В каждом занятии пробегаемся по неделям, когда оно повторяется.
                foreach (int number in workDay.repeatAt)
                {
                    // Плюсуем к временной дате (номер недели - 1, т.к. чтобы перейти
                    // к первой неделе не нужно плюсовать неделю) * 7 дней) и
                    // приводим к локальной временной зоне.
                    iCalDateTime StartClass = new iCalDateTime(tmpDate.AddDays((number - 1) * 7).Local);

                    // Если неделя первая (подразумевается, что она не полная)
                    // и день занятий раньше для начала учебы, тогда не записываем его.
                    if ((number == 1
                        && StartClass.LessThan(startStudy))
                        ||
                        (StartClass.GreaterThanOrEqual(new iCalDateTime(startStudy.FirstDayOfYear.AddDays(363)))
                        && !(isLeapYear(StartClass.Year)))
                        ||
                        (StartClass.GreaterThanOrEqual(new iCalDateTime(startStudy.FirstDayOfYear.AddDays(364)))
                        && isLeapYear(StartClass.Year)))
                        continue;

                    Event newClass = CalForSchedule.Create<Event>();

                    newClass.DTStart = StartClass;
                    newClass.DTStart = newClass.DTStart.Add(workDay.timeClassStart);
                    newClass.Duration = workDay.timeClassEnd - workDay.timeClassStart;
                    newClass.Summary = string.Format("{0}", workDay.nameSubject);
                    newClass.Description = string.Format("Преподаватель: {0}", workDay.nameLecturer);
                    newClass.Location = string.Format("{0}, {1}", workDay.typeClass, workDay.place);
                    newClass.IsAllDay = false;

                    // Добавим напоминание к парам, чтобы не забыть о них.
                    Alarm alarm = new Alarm();
                    alarm.Trigger = new Trigger(TimeSpan.FromMinutes(-5));
                    alarm.Description = "Напоминание о событии";
                    alarm.AddProperty("ACTION", "DISPLAY");
                    newClass.Alarms.Add(alarm);

                    // Если это первая пара за день, напоминаем о ней за 2,5 часа.
                    if (workDay.isFirstClassesOfADay)
                    {
                        Alarm alarm2 = new Alarm();
                        alarm2.Trigger = new Trigger(TimeSpan.FromMinutes(-150));
                        alarm2.Description = "Напоминание о событии";
                        alarm2.AddProperty("ACTION", "DISPLAY");
                        newClass.Alarms.Add(alarm2);
                    }
                }
            }

            // Сериализуем наш календарь.
            iCalendarSerializer serializer = new iCalendarSerializer();
            serializer.Serialize(CalForSchedule, "Расписание.ics");
            Console.WriteLine("Календарь расписания сохранён успешно" + Environment.NewLine);
        }
        /// <summary>
        /// This method is used when Start and End time both are supplied
        /// </summary>
        /// <param name="title"></param>
        /// <param name="body"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <param name="location"></param>
        /// <param name="organizer"></param>
        /// <param name="eventId"></param>
        /// <param name="allDayEvent"></param>
        /// <returns></returns>
        private static string CreateCalendarEvent(string title, string body, DateTime startDate, DateTime endDate, string location, string organizer, string eventId, bool allDayEvent)
        {
            var iCal = new iCalendar
            {
                Method = "PUBLISH", //PUBLISH
                Version = "2.0"
            };
            // Create the event
            var evt = iCal.Create<Event>();
            //Subject
            evt.Summary = title;
            //Start Time
            evt.Start = new iCalDateTime(startDate.Year,
                                         startDate.Month, startDate.Day, startDate.Hour,
                                         startDate.Minute, startDate.Second);
            //End Time
            evt.End = new iCalDateTime(endDate.Year,
                                         endDate.Month, endDate.Day, endDate.Hour,
                                         endDate.Minute, endDate.Second);
            //Description of the Event
            evt.Description = body;
            //Location for the Event
            evt.Location = location;
            //Is All Day flag
            evt.IsAllDay = allDayEvent;
            //Event Id
            evt.UID = new Guid().ToString();

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

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

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

            evt.Alarms.Add(alarm);

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

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

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

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

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

            evt.IsAllDay = allDayEvent;

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

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

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

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

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

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

            evt.Alarms.Add(alarm);

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

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

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

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

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

            // Set the longer description of the event
            evt.Description = "A more in-depth description of this event.";
            
            // Set the event to start at 11:00 A.M. New York time on January 2, 2007.
            evt.Start = new iCalDateTime(2007, 1, 2, 11, 0, 0, "America/New_York", iCal);

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

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

            // Set the geographic location (latitude,longitude) of the event
            evt.Geo = new Geo(114.2938, 32.982);
            
            evt.Location = "Home office";
            evt.Priority = 7;

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

            // Add a person who will attend the event
            evt.AddAttendee("*****@*****.**");

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

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

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

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

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

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

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

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

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

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

            // Set the alarm to repeat twice (for a total of 3 alarms)
            // before the event.  Each repetition will occur 10 minutes
            // after the initial alarm.  In english - that means
            // the alarm will go off 30 minutes before the event,
            // then again 20 minutes before the event, and again
            // 10 minutes before the event.
            alarm.Repeat = 2;
            alarm.Duration = TimeSpan.FromMinutes(10);
            
            // Add the alarm to the event
            evt.AddAlarm(alarm);
                        
            // Create another (much more simple) event
            evt = iCal.Create<Event>();
            evt.Summary = "Every month on the 21st";
            evt.Description = "A more in-depth description of this event.";
            evt.Start = new iCalDateTime(2007, 1, 21, 16, 0, 0, "America/New_York", iCal);
            evt.Duration = TimeSpan.FromHours(1.5);

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

            return iCal;
        }
        protected void Submit_click(object sender, EventArgs e)
        {
            var allDays = new List<IWeekDay>()
                              {
                                  new WeekDay(DayOfWeek.Sunday),
                                  new WeekDay(DayOfWeek.Monday),
                                  new WeekDay(DayOfWeek.Tuesday),
                                  new WeekDay(DayOfWeek.Wednesday),
                                  new WeekDay(DayOfWeek.Thursday),
                                  new WeekDay(DayOfWeek.Friday),
                                  new WeekDay(DayOfWeek.Saturday),
                              };

            var weekdays = allDays.Where(d => d.DayOfWeek != DayOfWeek.Saturday && d.DayOfWeek != DayOfWeek.Sunday).ToList();

            var iCal = new iCalendar();
            var evt = iCal.Create<Event>();
            evt.Summary = title.Value;
            evt.Start = new iCalDateTime(DateTime.Parse(start.Value));
            evt.End = new iCalDateTime(DateTime.Parse(end.Value));

            var rp = new RecurrencePattern();
            switch (freq.Value)
            {
                case "DAILY":
                    rp = new RecurrencePattern { Frequency = FrequencyType.Daily };

                    if (repeat.SelectedValue == "everyWeekday")
                    {
                        rp.ByDay = weekdays;
                    }
                    else if (repeat.SelectedValue == "everyDay")
                    {
                        rp.ByDay = allDays;
                    }

                    break;
                case "WEEKLY":
                    rp = new RecurrencePattern { Frequency = FrequencyType.Weekly };
                    rp.Interval = Int32.Parse(interval.Value);
                    foreach (var item in byweekday.Items)
                    {
                        var listItem = item as ListItem;
                        if (listItem.Selected)
                        {
                            rp.ByDay.Add(new WeekDay(listItem.Value));
                        }
                    }
                    break;
            }

            rp.Until = DateTime.Parse(until.Value);

            evt.RecurrenceRules.Add(rp);

            occurrences.InnerText = "";
            var occurrenceDates = evt.GetOccurrences(evt.Start.Date, rp.Until);

            foreach (var occ in occurrenceDates)
            {
                occurrences.Controls.Add(new HtmlGenericControl("div"){ InnerText = occ.ToString()});
            }
        }
Exemple #26
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"));
        }
    public bool SendMail()
    {
        try
        {
            SmtpClient sc = new SmtpClient("smtp.gmail.com");
            sc.Port = 587;
            sc.Credentials = new System.Net.NetworkCredential("username", "password");
            sc.EnableSsl = true;

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

            iCalendar iCal = new iCalendar();

            iCal.Method = "REQUEST";

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

            evt.Summary = strSummary;
            evt.Start = new iCalDateTime(dtStartTime.Year, dtStartTime.Month, dtStartTime.Day, dtStartTime.Hour, dtStartTime.Minute, dtStartTime.Second);
            evt.End = new iCalDateTime(dtEndTime.Year, dtEndTime.Month, dtEndTime.Day, dtEndTime.Hour, dtEndTime.Minute, dtEndTime.Second);
            evt.Description = strDescription;
            evt.Location = strLocation;

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

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

            AlternateView loTextView = null;
            AlternateView loHTMLView = null;
            AlternateView loCalendarView = null;

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

            // Add parameters to the calendar header
            loCalendarType.Parameters.Add("method", "REQUEST");
            loCalendarType.Parameters.Add("name", "meeting.ics");

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

            loHTMLView = AlternateView.CreateAlternateViewFromString(icalData, loHTMLType);
            msg.AlternateViews.Add(loHTMLView);

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

            sc.Send(msg);
            return true;
        }
        catch (Exception ex)
        {
            SingletonLogger.Instance.Error("MailAppointment.SendMail", ex);
            return false;
        }
    }
        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");
        }
        public static void Main(string[] args)
        {
            // Адрес сайта, откуда будем парсить данные.
            string WebAddress = @"http://www.sports.ru/barcelona/calendar/";

            // Создаём экземляры классов веб-страницы и веб-документа
            HtmlWeb WebGet = new HtmlWeb();
            // Загружаем html-документ с указанного сайта.
            HtmlDocument htmlDoc = WebGet.Load(WebAddress);

            // Сюда будем сохранять матчи
            Matches MatchesFC = new Matches();

            // Парсим название клуба (удаляя символ возрата каретки)
            MatchesFC.NameFC = htmlDoc.DocumentNode.
                SelectSingleNode(".//*[@class='titleH1']").
                FirstChild.InnerText.Replace("\r\n", "");

            // Находим в этом документе таблицу с датами матчей с помощью XPath-выражений.
            HtmlNode Table = htmlDoc.DocumentNode.SelectSingleNode(".//*[@class='stat-table']/tbody");
            // Из полученной таблицы выделяем все элементы-строки с тегом "tr".
            IEnumerable<HtmlNode> rows = Table.Descendants().Where(x => x.Name == "tr");

            foreach (var row in rows)
            {
                // Создаём коллекцию из ячеек каждой строки.
                HtmlNodeCollection cells = row.ChildNodes;
                // Создаём экземпляр класса SingleMatch, чтобы затем добавить его в лист.
                SingleMatch match = new SingleMatch();

                // Парсим дату, предварительно убирая из строки символ черточки "|",
                // иначе наш метод TryParse не сможет правильно обработать.
                DateTime time;
                DateTime.TryParse(cells[1].InnerText.Replace("|", " "), out time);
                match.StartTime = time;

                // Остальные поля просто заполняем, зная нужный нам индекс.
                match.Tournament = cells[3].InnerText;
                // В ячейке "Соперник" нужно удалить символ неразрывного пробела ("&nbsp")
                match.Rival = cells[5].InnerText.Replace("&nbsp;", "");
                match.Place = cells[6].InnerText;

                // Добавляем одиночный матч в лист матчей.
                MatchesFC.ListMatches.Add(match);
            }

            // Создаём календарь, в который будем сохранять матчи.
            iCalendar CalForMatches = new iCalendar
            {
                Method = "PUBLISH",
                Version = "2.0"
            };
            // Эти настройки нужны для календаря Mac, чтобы он был неотличим от
            // оригинального календаря (т.е. созданного внутри Mac Calendar)
            CalForMatches.AddProperty("CALSCALE", "GREGORIAN");
            CalForMatches.AddProperty("X-WR-CALNAME", "Mатчи ФК " + MatchesFC.NameFC);
            CalForMatches.AddProperty("X-WR-TIMEZONE", "Europe/Moscow");
            CalForMatches.AddLocalTimeZone();

            // Сохраняем полученный результат.
            foreach (SingleMatch match in MatchesFC.ListMatches)
            {
                Event newMatch = CalForMatches.Create<Event>();

                newMatch.DTStart = new iCalDateTime(match.StartTime);
                newMatch.Duration = new TimeSpan(2, 30, 0);
                newMatch.Summary = string.Format("{0} : {1}", MatchesFC.NameFC, match.Rival);
                newMatch.Description = string.Format("{0}. {1} : {2}, {3}",
                    match.Tournament, MatchesFC.NameFC, match.Rival, match.Place);

                // Добавим напоминание к матчам, чтобы не забыть о них
                Alarm alarm = new Alarm();
                alarm.Trigger = new Trigger(TimeSpan.FromMinutes(-10));
                alarm.Description = "Напоминание о событии";
                alarm.AddProperty("ACTION", "DISPLAY");
                newMatch.Alarms.Add(alarm);
            }

            // Сериализуем наш календарь.
            iCalendarSerializer serializer = new iCalendarSerializer();
            serializer.Serialize(CalForMatches, MatchesFC.NameFC + ".ics");
            Console.WriteLine("Календарь матчей сохранён успешно" + Environment.NewLine);

            return;
        }
        public 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");
        }
    public void SendMail()
    {
        SmtpClient sc = new SmtpClient("smtp.gmail.com");
        sc.Port = 587;
        sc.Credentials = new System.Net.NetworkCredential("username", "password");
        sc.EnableSsl = true;

        MailMessage msg = new MailMessage();
        msg.From = new MailAddress("*****@*****.**", "Đại bàng Dép Đứt");
        msg.To.Add(new MailAddress("*****@*****.**", "Chim én Dép Đứt :))"));
        msg.To.Add(new MailAddress("*****@*****.**", "Chim én Dép Đứt 222 :))"));
        msg.Subject = "Sát thủ đầu mưng mủ";
        msg.Body = "Một khi đã máu thì đừng hỏi bố cháu là ai :))";

        iCalendar iCal = new iCalendar();

        iCal.Method = "REQUEST";

        DateTime startTime = DateTime.Now.AddMinutes(16);
        DateTime endTime = startTime.AddMinutes(10);

        //Todo evt = iCal.Create<Todo>();

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

        evt.Summary = "Một khi đã quyết chỉ có nản mới cản được anh.";
        evt.Start = new iCalDateTime(startTime.Year, startTime.Month, startTime.Day, startTime.Hour, startTime.Minute, startTime.Second);
        //evt.End = evt.Start.AddMinutes(30);
        evt.Description = "Chi tiết appointment";
        evt.Location = "Cái location chắc ko cần";

        //evt.Organizer = new Organizer("Phats");

        Alarm alarm = new Alarm();
        alarm.Action = AlarmAction.Display;
        alarm.Summary = "Nội dung alarm nà";
        alarm.Trigger = new Trigger(TimeSpan.FromMinutes(-14));
        evt.Alarms.Add(alarm);

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

        System.Net.Mail.Attachment attachment = System.Net.Mail.Attachment.CreateAttachmentFromString(icalData, new System.Net.Mime.ContentType("text/calendar"));
        attachment.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
        attachment.Name = "EventDetails.ics"; //not visible in outlook



        AlternateView loTextView = null;
        AlternateView loHTMLView = null;
        AlternateView loCalendarView = null;

        // Set up the different mime types contained in the message
        System.Net.Mime.ContentType loTextType = new System.Net.Mime.ContentType("text/plain");
        System.Net.Mime.ContentType loHTMLType = new System.Net.Mime.ContentType("text/html");
        System.Net.Mime.ContentType loCalendarType = new System.Net.Mime.ContentType("text/calendar");
        // Add parameters to the calendar header
        loCalendarType.Parameters.Add("method", "REQUEST");
        loCalendarType.Parameters.Add("name", "meeting.ics");

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

        loHTMLView = AlternateView.CreateAlternateViewFromString(icalData, loHTMLType);
        msg.AlternateViews.Add(loHTMLView);

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



        //msg.Attachments.Add(attachment);

        sc.Send(msg);

    }
        public bool TryAddCourse(uint courseId, string courseString, string sectionCode, iCalendar calendar)
        {
            IIndexableCollection<Course> courses = (IIndexableCollection<Course>)HttpContext.Current.Application["Courses"];
            Course course;
            if (courses.TryGetItem(courseId, out course))
            {
                if (!courseString.StartsWith(course.Abbr)) return false;
                foreach (CourseSection section in course.Sections)
                {
                    if (section.Name == sectionCode)
                    {
                        UTCourseSection utSection = section as UTCourseSection;
                        UTCourse utCourse = course as UTCourse;
                        if (utSection != null && utCourse != null)
                        {
                            int order = 0;
                            foreach (CourseSectionTimeSpan timeSpan in utSection.ParsedTime.MeetTimes)
                            {
                                if (utCourse.SemesterDetail == "Fall" || utCourse.SemesterDetail == "Year")
                                {
                                    Event courseEvent = calendar.Create<Event>();

                                    if (utCourse.Faculty == "Engineering")
                                    {
                                        courseEvent.Start = new iCalDateTime(this.ConvertDateTime(new DateTime(2016, 9, 8), timeSpan.Day, timeSpan.Start), "America/Toronto");
                                        courseEvent.End = new iCalDateTime(this.ConvertDateTime(new DateTime(2016, 9, 8), timeSpan.Day, timeSpan.End), "America/Toronto");
                                        courseEvent.RecurrenceRules.Add(new RecurrencePattern(FrequencyType.Weekly)
                                        {
                                            //Count = 13
                                            Until = new DateTime(2016, 12, 7)
                                        });
                                    }
                                    else
                                    {
                                        courseEvent.Start = new iCalDateTime(this.ConvertDateTime(new DateTime(2016, 9, 12), timeSpan.Day, timeSpan.Start), "America/Toronto");
                                        courseEvent.End = new iCalDateTime(this.ConvertDateTime(new DateTime(2016, 9, 12), timeSpan.Day, timeSpan.End), "America/Toronto");
                                        courseEvent.RecurrenceRules.Add(new RecurrencePattern(FrequencyType.Weekly)
                                        {
                                            //Count = 13
                                            Until = new DateTime(2016, 12, 6)
                                        });
                                    }

                                    courseEvent.Summary = utCourse.Abbr + ": " + utCourse.Name + " " + utSection.Name;
                                    try
                                    {
                                        courseEvent.Location = utSection.Location.Split(' ')[order];
                                    }
                                    catch
                                    {
                                    }
                                }

                                if (utCourse.SemesterDetail == "Winter" || utCourse.SemesterDetail == "Year")
                                {
                                    Event courseEvent = calendar.Create<Event>();

                                    if (utCourse.Faculty == "Engineering")
                                    {
                                        courseEvent.Start = new iCalDateTime(this.ConvertDateTime(new DateTime(2017, 1, 9), timeSpan.Day, timeSpan.Start), "America/Toronto");
                                        courseEvent.End = new iCalDateTime(this.ConvertDateTime(new DateTime(2017, 1, 9), timeSpan.Day, timeSpan.End), "America/Toronto");

                                        courseEvent.RecurrenceRules.Add(new RecurrencePattern(FrequencyType.Weekly)
                                        {
                                            Until = new DateTime(2017, 4, 13)
                                            //Count = 13
                                        });
                                    }
                                    else
                                    {
                                        courseEvent.Start = new iCalDateTime(this.ConvertDateTime(new DateTime(2017, 1, 5), timeSpan.Day, timeSpan.Start), "America/Toronto");
                                        courseEvent.End = new iCalDateTime(this.ConvertDateTime(new DateTime(2017, 1, 5), timeSpan.Day, timeSpan.End), "America/Toronto");

                                        courseEvent.RecurrenceRules.Add(new RecurrencePattern(FrequencyType.Weekly)
                                        {
                                            Until = new DateTime(2017, 4, 5)
                                            //Count = 13
                                        });
                                    }
                                    courseEvent.Summary = utCourse.Abbr + ": " + utCourse.Name + " " + utSection.Name;
                                    try
                                    {
                                        courseEvent.Location = utSection.Location.Split(' ')[order];
                                    }
                                    catch
                                    {
                                    }
                                }
                                order++;
                            }
                        }
                        return true;
                    }
                }
            }
            return false;
        }
Exemple #33
0
        /// <summary>
        /// Writes the showscases ical.
        /// </summary>
        private static void WriteShowscasesIcal()
        {
            string tzid = iCalTimeZone.FromLocalTimeZone().TZID;

            // Write out a calendar of each showcase.
            iCalendar showcasesCalendar = new iCalendar();
            showcasesCalendar.AddLocalTimeZone();

            foreach (Showcase showcase in _showcases.Where(s => s.Performances.Count > 0))
            {
                Event entry = showcasesCalendar.Create<Event>();
                entry.DTStamp = new iCalDateTime(showcase.Doors);
                entry.UID = GetMD5Hash(string.Format("{0}{1}", showcase.Doors.Ticks.ToString(), showcase.Name));
                entry.Start = new iCalDateTime(showcase.Doors, tzid);
                entry.End = new iCalDateTime(showcase.Performances.OrderBy(p => p.EndTime).Last().EndTime, tzid);
                entry.IsAllDay = false;
                entry.Location = showcase.Venue;
                entry.Summary = showcase.Name;

                foreach (Performance performance in showcase.Performances)
                {
                    entry.Description += string.Format(
                        "{0} ({1}): {2} - {3}\n",
                        performance.Artist.Name,
                        performance.PerformanceType,
                        performance.StartTime.ToString("h:mm tt"),
                        performance.EndTime.ToString("h:mm tt"));
                }

                entry.Description += string.Format(
                    "\n{0}\n{1}\n\nTickets\n{2}\n\nAll Ages? {3}\nIncluded in pass? {4}{5}",
                    showcase.Name,
                    showcase.ShowcaseLink,
                    showcase.TicketLink,
                    showcase.IsAllAges ? "yes" : "no",
                    showcase.IsIncludedWithPass ? "yes" : "no",
                    showcase.SetTimesAreEstimated ? "\n\nWarning: Set times are estimated for this showcase and are almost certainly incorrect." : string.Empty);
            }

            new iCalendarSerializer().Serialize(showcasesCalendar, Path.Combine(_dataDirectory, "showcases.ics"));
        }
        private iCalendar ConvertAppointmentToIcalendar(Appointment ap)
        {
            var ics = new iCalendar { ProductID = this.ProductId };

            var evt = ics.Create<Event>();

            // Event description and main properties
            evt.Summary = ap.Subject;
            evt.Description = ap.Details;
            evt.Organizer = new Organizer(ap.Organizer.Address) { CommonName = ap.Organizer.DisplayName };
            evt.Url = ap.Uri;

            // Time
            evt.Start = new iCalDateTime(ap.StartTime.UtcDateTime);
            evt.Start.SetTimeZone(iCalTimeZone.FromSystemTimeZone(TimeZoneInfo.Utc));
            evt.Duration = ap.Duration;
            evt.IsAllDay = ap.AllDay;
            
            // Location
            evt.Location = ap.Location;
            
            // TODO: recurrence
            
            // Reminder
            if (ap.Reminder != null)
            {
                var reminderSource = (TimeSpan) ap.Reminder;
                evt.Alarms.Add(new Alarm
                {
                    //Duration = ap.Reminder,
                    Trigger = new Trigger(reminderSource),
                    //Action = AlarmAction.Audio,
                    //Description = "Reminder"
                });
            }

            return ics;
        }