Ejemplo n.º 1
0
        public void AddingExdateToEventShouldNotBeEqualToOriginal()
        {
            //Create a calendar with an event with a recurrence rule
            //Serialize to string, and deserialize
            //Change the original calendar.Event to have an ExDate
            //Serialize to string, and deserialize
            //Event and Calendar hash codes and equality should NOT be the same
            var serializer = new CalendarSerializer();

            var vEvent = GetSimpleEvent();

            vEvent.RecurrenceRules = GetSimpleRecurrenceList();
            var cal1 = new Calendar();

            cal1.Events.Add(vEvent);
            var serialized           = serializer.SerializeToString(cal1);
            var deserializedNoExDate = Calendar.LoadFromStream(new StringReader(serialized)).First() as Calendar;

            Assert.AreEqual(cal1, deserializedNoExDate);

            vEvent.ExceptionDates = GetExceptionDates();
            serialized            = serializer.SerializeToString(cal1);
            var deserializedWithExDate = Calendar.LoadFromStream(new StringReader(serialized)).First() as Calendar;

            Assert.AreNotEqual(deserializedNoExDate.Events.First(), deserializedWithExDate.Events.First());
            Assert.AreNotEqual(deserializedNoExDate.Events.First().GetHashCode(), deserializedWithExDate.Events.First().GetHashCode());
            Assert.AreNotEqual(deserializedNoExDate, deserializedWithExDate);
        }
        /// <summary>
        /// Generate the calendar events for the last month
        /// Probably NOT USED
        /// </summary>
        /// <param name="currentUserName"></param>
        /// <param name="bookingsLastMonth"></param>
        /// <returns></returns>
        public string GenerateCalendarEventsForSeatBookings(string currentUserName, IEnumerable <SeatBooking> bookingsLastMonth)
        {
            //get back all the calender events for the last month
            string allevents = null;
            //pass in all the booking events.
            var seatBooking = bookingsLastMonth;

            //calendar as string to be outputted to screen and sent to email
            allevents += _calService.CalendarBooking(seatBooking, true);

            Calendar cal = new Calendar();

            cal = _dbCallsSessionData.SeatBookingsCalOutputToEmail;


            var serializer = new CalendarSerializer();

            foreach (var evCalEvent in cal.Events)
            {
                var serializedCalendar = serializer.SerializeToString(evCalEvent);
                _emailSender.SendEmailAsync(currentUserName, "NZBat Booking", serializedCalendar);
                //outputted to email and saved to show on screen
                allevents += serializedCalendar;
            }

            return(allevents);
        }
        /// <summary>
        /// Events sent back as calendar events string
        /// </summary>
        /// <param name="CurrentUserName"></param>
        /// <returns></returns>
        public string CalendarEventsForEmail(string CurrentUserName)
        {
            //https://stackoverflow.com/questions/46985663/use-ical-net-to-send-meeting-invite-for-microsoft-outlook
            //https://github.com/rianjs/ical.net/wiki

            string allevents = "";
            //get back a list of the calendar events created in SeatBookingController
            var seatBooking = _dbCallsSessionData.AllSeatBookings;

            //calendar as string to be outputted to screen
            allevents += _calService.CalendarBooking(seatBooking, false);

            Calendar cal = new Calendar();

            cal = _dbCallsSessionData.SeatBookingsCalOutputToEmail;


            var serializer = new CalendarSerializer();

            foreach (var evCalEvent in cal.Events)
            {
                var serializedCalendar = serializer.SerializeToString(evCalEvent);
                _emailSender.SendEmailAsync(CurrentUserName, "NZBat Booking", serializedCalendar);
                //outputted to email and saved to show on screen
                allevents += serializedCalendar;
            }

            _logger.LogInformation("CalendarEventsForEmail emails = {name}", allevents);

            return(allevents);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Processes the request.
        /// </summary>
        /// <param name="httpContext">The HTTP context.</param>
        public void ProcessRequest(HttpContext httpContext)
        {
            string interactionDeviceType = InteractionDeviceType.GetClientType(httpContext.Request.UserAgent);

            try
            {
                CalendarProps calendarProps = ValidateRequestData(httpContext);

                if (calendarProps == null)
                {
                    return;
                }

                var icalendar = CreateICalendar(calendarProps, interactionDeviceType);

                var    serializer = new CalendarSerializer();
                string s          = serializer.SerializeToString(icalendar);

                httpContext.Response.Clear();
                httpContext.Response.ClearHeaders();
                httpContext.Response.ClearContent();
                httpContext.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}_ical.ics", RockDateTime.Now.ToString("yyyy-MM-dd_hhmmss")));
                httpContext.Response.ContentType = "text/calendar";
                httpContext.Response.Write(s);
            }
            catch (Exception ex)
            {
                ExceptionLogService.LogException(ex, httpContext);
                SendBadRequest(httpContext);
            }
        }
Ejemplo n.º 5
0
        public static byte[] CreateIcal()
        {
            var iCal      = new Calendar();
            var wEuropeST = TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time");

            iCal.AddTimeZone(wEuropeST);
            WebClient webClient = new WebClient();

            webClient.Encoding = Encoding.UTF8;
            string[] items = webClient.DownloadString("http://hvmkblg.github.io/ross/ross.txt" + "?ticks=" + DateTime.Now.Ticks.ToString()).Split('$');

            foreach (string item in items)
            {
                if (items.Length == 0)
                {
                    continue;
                }
                var parsedItem = ItemBL.CreateItem(item);
                if (parsedItem != null)
                {
                    iCal.Events.Add(ItemBL.ToEvent(parsedItem));
                }
            }

            var    serializer = new CalendarSerializer();
            string result     = serializer.SerializeToString(iCal);

            byte[] bytes = Encoding.UTF8.GetBytes(result);

            return(bytes);
        }
Ejemplo n.º 6
0
        private static void WriteCalenderToFile(Calendar calendar, string file)
        {
            var serializer         = new CalendarSerializer();
            var serializedCalendar = serializer.SerializeToString(calendar);

            File.WriteAllText(file, serializedCalendar);
        }
Ejemplo n.º 7
0
        public void VTimeZonePacificKiritimatiShouldSerializeProperly()
        {
            var iCal       = CreateTestCalendar("Pacific/Kiritimati");
            var serializer = new CalendarSerializer();

            Assert.DoesNotThrow(() => serializer.SerializeToString(iCal));
        }
Ejemplo n.º 8
0
        private static string CreateCalendarEntry(DateTime?start, DateTime?end, string title, string description, string location)
        {
            Calendar iCal = new Calendar();

            iCal.Method = "PUBLISH";
            // Create the event, and add it to the iCalendar
            CalendarEvent evt = iCal.Create <CalendarEvent>();

            // Set information about the event
            evt.Start       = new CalDateTime(start.Value);
            evt.End         = new CalDateTime(end.Value); // This also sets the duration
            evt.Description = description;
            evt.Location    = location;
            evt.Summary     = title;
            // Create a reminder 24h before the event
            Alarm reminder = new Alarm();

            reminder.Action  = AlarmAction.Display;
            reminder.Trigger = new Trigger(new TimeSpan(-24, 0, 0));
            evt.Alarms.Add(reminder);

            var serializer         = new CalendarSerializer();
            var serializedCalendar = serializer.SerializeToString(iCal);

            //return iCal;
            return(serializedCalendar);
        }
Ejemplo n.º 9
0
        public async Task <HttpResponseMessage> MyCalendar(string id)
        {
            const string calExt = ".ics";

            if (!id.EndsWith(calExt))
            {
                id += calExt;
            }
            Guid userId             = Guid.Parse(id.Substring(0, id.Length - calExt.Length));
            var  courseParticipants = await(from cp in Repo.CourseParticipants.Include(cp => cp.Course.Department.Institution.Culture)
                                            let c = cp.Course
                                                    where cp.ParticipantId == userId && cp.IsConfirmed != false && DbFunctions.AddDays(c.StartFacultyUtc, c.CourseFormat.DaysDuration + 1) > DateTime.UtcNow
                                                    select cp).ToListAsync();

            var evts = Appointment.MapCoursesToEvents(courseParticipants);

            evts.AddRange(from cp in courseParticipants
                          where cp.IsFaculty && cp.Course.FacultyMeetingUtc.HasValue
                          select Appointment.CreateFacultyMeetingEvent(cp.Course));
            var cal        = Appointment.CreateCal(evts);
            var serializer = new CalendarSerializer();
            var stream     = serializer.SerializeToString(cal).ToStream();

            //should work but truncating the stream at the moment - ? flush needed in the ical.net source code
            return(StreamToResponse(stream, id));
        }
Ejemplo n.º 10
0
        private string ParseResponseToCalendar(Response response, string name)
        {
            var calendarEvents = new List <CalendarEvent>();

            foreach (var d in response.Data)
            {
                calendarEvents.Add(
                    new CalendarEvent
                {
                    End         = d.End_time == null ? new CalDateTime(ParseDateTime(d.Start_time).AddHours(1), "Europe/Vilnius") : new CalDateTime(ParseDateTime(d.End_time), "Europe/Vilnius"),
                    Start       = new CalDateTime(ParseDateTime(d.Start_time), "Europe/Vilnius"),
                    Summary     = d.Name,
                    Location    = d.Place != null ? d.Place.Name : "",
                    Description = (d.Place != null && d.Place.Location != null) ? $"{d.Place.Location.Street}, {d.Place.Location.City}\n{d.Description}\n\nRenginio nuoroda https://www.facebook.com/events/{d.Id}" : $"{d.Description}\n\nRenginio nuoroda https://www.facebook.com/events/{d.Id}"
                }
                    );
            }

            var calendar = new Ical.Net.Calendar();

            calendar.AddProperty("X-WR-CALNAME", name);
            calendar.AddProperty("X-WR-TIMEZONE", "Europe/Vilnius");
            calendar.AddProperty("METHOD", "PUBLISH");
            calendar.AddProperty("CALSCALE", "GREGORIAN");

            calendar.Events.AddRange(calendarEvents);

            var serializer = new CalendarSerializer();

            return(serializer.SerializeToString(calendar));
        }
        public ActionResult DownloadIcal(string downloadFileName)
        {
            ApplicationDbContext db = new ApplicationDbContext();
            var allEvents           = db.EventModels.ToList();
            var calendar            = new Ical.Net.Calendar();

            foreach (var e in allEvents)
            {
                calendar.Events.Add(new CalendarEvent
                {
                    Class       = "PUBLIC",
                    Summary     = e.Title,
                    Created     = new CalDateTime(DateTime.Now),
                    Description = e.Description,
                    Start       = new CalDateTime(Convert.ToDateTime(e.Start)),
                    End         = new CalDateTime(Convert.ToDateTime(e.End)),
                    Sequence    = 0,
                    Uid         = Guid.NewGuid().ToString(),
                    Location    = e.Location
                });
            }

            var          serializer         = new CalendarSerializer(new SerializationContext());
            var          serializedCalendar = serializer.SerializeToString(calendar);
            var          bytesCalendar      = Encoding.UTF8.GetBytes(serializedCalendar);
            MemoryStream ms = new MemoryStream(bytesCalendar);

            return(File(ms, "text/calendar", downloadFileName));
        }
Ejemplo n.º 12
0
        public async Task <IActionResult> ExportCalendar(string id)
        {
            var _ApplicantSessionController = new ApplicantSessionController(_context);
            var _formationController        = new FormationController(_context);
            IEnumerable <applicant_session> getApplicantSession = await _ApplicantSessionController.GetApplicantSession(id);

            var calendar = new Calendar();

            foreach (var item in getApplicantSession.ToList())
            {
                var f = _formationController.GetFormation(item.idFormation).Result.Value;
                calendar.Events.Add(new CalendarEvent
                {
                    Class       = "PUBLIC",
                    Summary     = f.Name,
                    Created     = new CalDateTime(DateTime.Now),
                    Start       = new CalDateTime(f.StartDate),
                    End         = new CalDateTime(f.EndDate),
                    Description = f.Description,
                    Location    = f.Location,
                    Organizer   = new Organizer
                    {
                        CommonName = f.OrganizationName + " : " + f.Former,
                    },
                });
            }

            var serializer         = new CalendarSerializer();
            var serializedCalendar = serializer.SerializeToString(calendar);
            var bytesCalendar      = System.Text.Encoding.UTF8.GetBytes(serializedCalendar);

            return(File(bytesCalendar, "application/octet-stream", "calendar.ics"));
        }
Ejemplo n.º 13
0
        public void SerializeDeserialize()
        {
            //ToDo: This test is broken as of 2016-07-13
            var cal1 = new Calendar
            {
                Method  = "PUBLISH",
                Version = "2.0"
            };

            var evt = new Event
            {
                Class        = "PRIVATE",
                Created      = new CalDateTime(2010, 3, 25, 12, 53, 35),
                DtStamp      = new CalDateTime(2010, 3, 25, 12, 53, 35),
                LastModified = new CalDateTime(2010, 3, 27, 13, 53, 35),
                Sequence     = 0,
                Uid          = "42f58d4f-847e-46f8-9f4a-ce52697682cf",
                Priority     = 5,
                Location     = "here",
                Summary      = "test",
                DtStart      = new CalDateTime(2012, 3, 25, 12, 50, 00),
                DtEnd        = new CalDateTime(2012, 3, 25, 13, 10, 00)
            };

            cal1.Events.Add(evt);

            var serializer         = new CalendarSerializer(new SerializationContext());
            var serializedCalendar = serializer.SerializeToString(cal1);

            using (var sr = new StringReader(serializedCalendar))
            {
                var cal2 = Calendar.LoadFromStream(sr)[0];
                CompareCalendars(cal1, cal2);
            }
        }
Ejemplo n.º 14
0
        public byte[] GetConferenceScheduleICal(int accountId, int conferenceId)
        {
            var entries = (_sessionRepository.GetSessionsForConferenceAndChairWithBaseEntryAttributes(accountId, conferenceId) as IEnumerable <BaseEntryEntity>).OrderBy(ent => ent.BeginDate).ToList();

            entries.AddRange((_sessionRepository.GetSpecialSessionsForConferenceAndChairWithBaseEntryAttributes(accountId, conferenceId) as IEnumerable <BaseEntryEntity>).OrderBy(ent => ent.BeginDate));
            entries = entries.OrderBy(ent => ent.BeginDate).ToList();

            var calendar = new Ical.Net.Calendar();

            foreach (var entry in entries)
            {
                calendar.Events.Add(new CalendarEvent
                {
                    Class       = "PUBLIC",
                    Summary     = (entry.GetType() == typeof(SessionDTO) ? "Session " : "Special session ") + entry.Title,
                    Created     = new CalDateTime(DateTime.Now),
                    Description = entry.GetType() == typeof(SessionDTO) ? ((SessionDTO)entry).Description : ((SpecialSessionDTO)entry).Description,
                    Start       = new CalDateTime(Convert.ToDateTime(entry.BeginDate)),
                    End         = new CalDateTime(Convert.ToDateTime(entry.EndDate)),
                    Sequence    = 0,
                    Uid         = Guid.NewGuid().ToString(),
                    Location    = entry.BuildingName + " r:" + entry.RoomCode,
                });
            }
            var serializer         = new CalendarSerializer(new SerializationContext());
            var serializedCalendar = serializer.SerializeToString(calendar);

            return(Encoding.UTF8.GetBytes(serializedCalendar));
        }
Ejemplo n.º 15
0
        public ActionResult DownloadiCal(int eventSlotId)
        {
            var eventTypes = _dataTypeProvider.GetEventTypes();
            var eventSlot  = _eventSlotRepository.GetById(eventSlotId);

            eventSlot.EventTypeName = eventTypes.SingleOrDefault(et => et.Id == eventSlot.EventTypeId)?.Name;

            var calendar = new Calendar();

            calendar.Events.Add(new CalendarEvent
            {
                Class   = "PUBLIC",
                Summary = eventSlot.EventTypeName, //TODO - Make this a better summary
                Created = new CalDateTime(DateTime.Now),
                //Description = res.Details,
                Start = new CalDateTime(eventSlot.Date),
                //End = new CalDateTime(Convert.ToDateTime(res.EndDate)),
                Sequence = 0,
                Uid      = Guid.NewGuid().ToString(),
                //Location = res.Location,
            });

            var serializer         = new CalendarSerializer(new SerializationContext());
            var serializedCalendar = serializer.SerializeToString(calendar);
            var bytesCalendar      = Encoding.UTF8.GetBytes(serializedCalendar);

            return(File(bytesCalendar, "text/calendar", "event.ics"));
        }
Ejemplo n.º 16
0
        public IActionResult DownloadCalendar()
        {
            List <BoatModel> boats = GetBoats();

            for (int i = 0; i < boats.Count; i++)
            {
                if (boats[i].ClosingDate.CompareTo(DateTime.Now) < 0)
                {
                    boats.RemoveAt(i);
                }
            }
            // Sort
            boats.Sort((s1, s2) => DateTimeOffset.Compare(s1.ClosingDate, s2.ClosingDate));

            // Create calendar
            var calendar = new Calendar();

            foreach (BoatModel boat in boats)
            {
                var icalEvent = new CalendarEvent
                {
                    Name        = boat.BoatName,
                    Description = string.Format("Type {0}", boat.ClosingType),
                    Start       = new CalDateTime(boat.ClosingDate),
                    End         = new CalDateTime(boat.ReopeningDate)
                };

                calendar.Events.Add(icalEvent);
            }

            var    iCalSerializer = new CalendarSerializer();
            string result         = iCalSerializer.SerializeToString(calendar);

            return(File(Encoding.ASCII.GetBytes(result), "calendar/text", "calendar.ics"));
        }
        public static MemoryStream ExportToIcs(List <VisitsRow> visits, AccessType accessType)
        {
            var model      = new Ical.Net.Calendar();
            var connection = SqlConnections.NewFor <VisitsRow>();

            foreach (var visit in visits)
            {
                var patient   = connection.ById <PatientsRow>(visit.PatientId);
                var cabinet   = connection.ById <CabinetsRow>(visit.CabinetId);
                var visitType = connection.ById <VisitTypesRow>(visit.VisitTypeId);

                var eventCalendar = new Ical.Net.CalendarEvent();
                eventCalendar.Uid      = $"{cabinet.CabinetId}_{visit.VisitId}@admin.myclario.com";
                eventCalendar.Location = cabinet.Name;

                eventCalendar.DtStart  = new CalDateTime((visit.StartDate ?? DateTime.Now));
                eventCalendar.DtEnd    = new CalDateTime((visit.EndDate ?? DateTime.Now));
                eventCalendar.IsAllDay = false;

                if (accessType == AccessType.Private)
                {
                    eventCalendar.Summary     = $"{patient.Name} - {visitType.Name}";
                    eventCalendar.Description = visit.Description;

                    if (!patient.Email.IsEmptyOrNull())
                    {
                        var attendee = new Attendee($"MAILTO:{patient.Email}");
                        attendee.CommonName          = patient.Name;
                        attendee.Rsvp                = true;
                        attendee.Role                = "REQ-PARTICIPANT";
                        attendee.ParticipationStatus = "NEEDS-ACTION";
                        attendee.Type                = "INDIVIDUAL";

                        eventCalendar.Attendees = new List <Attendee> {
                            attendee
                        };
                    }
                }
                else
                {
                    eventCalendar.Summary     = $"{visitType.Name}";
                    eventCalendar.Description = " ";
                }

                model.Events.Add(eventCalendar);
            }

            var          serializer = new CalendarSerializer(model);
            MemoryStream ms         = new MemoryStream();

            serializer.Serialize(model, ms, Encoding.UTF8);

            var ics   = serializer.SerializeToString(model);
            var bytes = System.Text.Encoding.UTF8.GetBytes(ics);

            ms.Write(bytes, 0, bytes.Length);
            ms.Seek(0, SeekOrigin.Begin);

            return(ms);
        }
Ejemplo n.º 18
0
        public byte[] GetTaskScheduleICal(int employeeId, int conferenceId)
        {
            var entries = GetTasksForEmployee(employeeId, conferenceId).ToList();

            var calendar = new Ical.Net.Calendar();

            foreach (var entry in entries)
            {
                calendar.Events.Add(new CalendarEvent
                {
                    Class       = "PUBLIC",
                    Summary     = "Task " + entry.Title,
                    Created     = new CalDateTime(DateTime.Now),
                    Description = entry.Description,
                    Start       = new CalDateTime(Convert.ToDateTime(entry.BeginDate)),
                    End         = new CalDateTime(Convert.ToDateTime(entry.EndDate)),
                    Sequence    = 0,
                    Uid         = Guid.NewGuid().ToString()
                });
            }
            var serializer         = new CalendarSerializer(new SerializationContext());
            var serializedCalendar = serializer.SerializeToString(calendar);

            return(Encoding.UTF8.GetBytes(serializedCalendar));
        }
Ejemplo n.º 19
0
        // GET: Reservations/GetIcal
        public async Task <IActionResult> GetIcalAsync()
        {
            var Reservations = await _reservationRepository.GetReservations(DateTime.Now.AddMonths(-1));

            var calendar = new Calendar();

            foreach (var item in Reservations)
            {
                calendar.Events.Add(
                    new CalendarEvent
                {
                    Summary     = $"Rezerwacja {item.ObjectForRent.Name}",
                    Start       = new CalDateTime(item.CheckIn),
                    End         = new CalDateTime(item.CheckOut),
                    Description = $"{item.Customer.FirstName} {item.Customer.LastName}\n" +
                                  $"Ilość osób: {item.People}\n" +
                                  $"Zaliczka: {item.ReservationDeposit}\n" +
                                  $"Całość: {item.ReservationPrice}\n",
                }
                    );
            }

            var serializer = new CalendarSerializer();
            var icalString = serializer.SerializeToString(calendar);

            return(File(Encoding.UTF8.GetBytes(icalString), "text/plain", "Calendar.ics"));
        }
Ejemplo n.º 20
0
        public async Task <string> GenerateOnboardingCalendarEventsAsync()
        {
            var organizationsOnboardingEventsDto =
                await _organizationsRepository.GetOrganizationsOnboardingEventsDataAsync()
                .ConfigureAwait(false);

            var calendar = new Calendar();

            calendar.AddTimeZone(timeZone);
            foreach (var eventDto in organizationsOnboardingEventsDto)
            {
                var linkToOrg = UrlHelper.UrlCombine(_baseFrontendUrl, EditOrganizationPath)
                                .Replace("{organizationId}", eventDto.Id.ToString(), StringComparison.InvariantCultureIgnoreCase);
                var icalEvent = new CalendarEvent
                {
                    Uid         = eventDto.Id.ToString(),
                    Summary     = eventDto.Name,
                    Description = $"Onboarding Kontakt:\n\n{eventDto.SupportPersonName}, {eventDto.SupportPersonEmail}.\n\nLink zum bearbeiten der Organisation:\n\n{linkToOrg}",
                    Location    = eventDto.City,
                    Start       = new CalDateTime(eventDto.OnboardingTimestamp, timeZone),
                    End         = new CalDateTime(eventDto.OnboardingTimestamp.AddHours(eventDurationInHours), timeZone),
                    Organizer   = new Organizer()
                    {
                        CommonName = eventDto.SupportPersonName,
                        Value      = new Uri($"mailto:{eventDto.SupportPersonEmail}")
                    }
                };

                calendar.Events.Add(icalEvent);
            }

            var iCalSerializer = new CalendarSerializer();

            return(iCalSerializer.SerializeToString(calendar));
        }
Ejemplo n.º 21
0
        private static string generateCalendarFile(List <MyCalendarEvent> calendarEvents)
        {
            var calendar = new Ical.Net.Calendar();

            foreach (MyCalendarEvent calendarEvent in calendarEvents)
            {
                var ca = new CalendarEvent
                {
                    Class       = "PUBLIC",
                    Summary     = calendarEvent.SummaryText,
                    Created     = new CalDateTime(DateTime.Now),
                    Description = calendarEvent.Details,
                    Start       = new CalDateTime(Convert.ToDateTime(calendarEvent.BeginDate)),
                    End         = new CalDateTime(Convert.ToDateTime(calendarEvent.EndDate)),
                    Sequence    = 0,
                    Uid         = Guid.NewGuid().ToString(),
                    Location    = calendarEvent.LocationText,
                };
                ca.Alarms.Add(new Alarm {
                    Summary = calendarEvent.SummaryText, Trigger = new Trigger(TimeSpan.FromMinutes(-15)), Action = AlarmAction.Display
                });
                ca.Alarms.Add(new Alarm {
                    Summary = calendarEvent.SummaryText, Trigger = new Trigger(TimeSpan.FromMinutes(-180)), Action = AlarmAction.Display
                });
                ca.Alarms.Add(new Alarm {
                    Summary = calendarEvent.SummaryText, Trigger = new Trigger(TimeSpan.FromMinutes(-1440)), Action = AlarmAction.Display
                });

                calendar.Events.Add(ca);
            }
            var serializer         = new CalendarSerializer(new SerializationContext());
            var serializedCalendar = serializer.SerializeToString(calendar);

            return(serializedCalendar);
        }
Ejemplo n.º 22
0
        public void AddOrUpdate(string id, Calendar cal)
        {
            var serializer = new CalendarSerializer(new SerializationContext());
            var bytes      = CalendarEncoding.GetBytes(serializer.SerializeToString(cal));

            _dict.AddOrUpdate(id.ToUpper(), bytes, (oldId, old) => bytes);
        }
Ejemplo n.º 23
0
        public static void SendCalendarEvent(Calendar calendar)
        {
            CalendarSerializer serializer = new CalendarSerializer(new SerializationContext());

            //preparing message
            MailMessage msg = new MailMessage();

            msg.From = new MailAddress("*****@*****.**", "Credit Inquiry");
            msg.To.Add(new MailAddress("*****@*****.**", "Song John"));
            msg.To.Add(new MailAddress("*****@*****.**", "jpi"));
            msg.Subject = "CS Inquiry";

            System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType("text/calendar");
            ct.Parameters.Add("method", "REQUEST");
            ct.Parameters.Add("name", "meeting.ics");
            AlternateView avCal = AlternateView.CreateAlternateViewFromString(serializer.SerializeToString(calendar), ct);

            msg.AlternateViews.Add(avCal);



            // sending
            SmtpClient sc = new SmtpClient("smtp.office365.com", 587);

            sc.UseDefaultCredentials = false;
            sc.Credentials           = new System.Net.NetworkCredential("username", "password");
            sc.DeliveryMethod        = SmtpDeliveryMethod.Network;
            sc.EnableSsl             = true;

            sc.Send(msg);
        }
Ejemplo n.º 24
0
        private static void ExportToIcs(List <AurionCalendarEvent> listCalendarEvent, string path)
        {
            var calendar = new Calendar();

            calendar.AddTimeZone(new VTimeZone("Europe/Paris"));
            foreach (var calendarEvent in listCalendarEvent)
            {
                var evt = new CalendarEvent
                {
                    Start    = new CalDateTime(Convert.ToDateTime(calendarEvent.Start)),
                    End      = new CalDateTime(Convert.ToDateTime(calendarEvent.End)),
                    IsAllDay = calendarEvent.AllDay,
                    Summary  = calendarEvent.Title
                };
                calendar.Events.Add(evt);
            }

            var serializer         = new CalendarSerializer();
            var serializedCalendar = serializer.SerializeToString(calendar);

            using (var file = new StreamWriter(path))
            {
                file.Write(serializedCalendar);
            }
        }
Ejemplo n.º 25
0
 public byte[] GetCalendarBytes(Encoding encoding)
 {
     for (int i = 0; i < Providers.Length; i++)
     {
         var prov = Providers[i];
         if (prov.UseBytes)
         {
             var bytes = prov.GetCalendarBytes(Filters);
             if (bytes != null)
             {
                 return(bytes);
             }
         }
         else
         {
             var cal = prov.GetCalendar(Filters);
             if (cal != null)
             {
                 var serializer = new CalendarSerializer(new SerializationContext());
                 return(encoding.GetBytes(serializer.SerializeToString(cal)));
             }
         }
     }
     return(null);
 }
Ejemplo n.º 26
0
        private static string CreateCalendar()
        {
            var now   = DateTime.Now;
            var later = now.AddHours(1);

            var e = new CalendarEvent
            {
                Start = new CalDateTime(now),
                End   = new CalDateTime(later),
            };

            var attendee = new Attendee
            {
                CommonName = "Ivan Saito",
                Rsvp       = true,
                Value      = new Uri("mailto:[email protected]")
            };

            e.Attendees = new List <Attendee> {
                attendee
            };


            var calendar = new Calendar();

            calendar.Events.Add(e);

            var serializer = new CalendarSerializer();
            var icalString = serializer.SerializeToString(calendar);

            return(icalString);
        }
Ejemplo n.º 27
0
        public ActionResult ExportCal()
        {
            var cal       = new Ical.Net.Calendar();
            var calEvents = Ctx.CalendarEvents;

            foreach (var item in calEvents)
            {
                cal.Events.Add(new Ical.Net.CalendarComponents.CalendarEvent {
                    Class       = "public",
                    Summary     = item.Title,
                    Created     = new CalDateTime(DateTime.Now),
                    Description = item.Desc,
                    Start       = new CalDateTime(Convert.ToDateTime(item.Start)),
                    End         = new CalDateTime(Convert.ToDateTime(item.End)),
                    Sequence    = 0,
                    Uid         = Guid.NewGuid().ToString(),
                    Location    = "N/A"
                });
            }
            var serializer         = new CalendarSerializer(new SerializationContext());
            var serializedCalendar = serializer.SerializeToString(cal);
            var bytesCalendar      = Encoding.UTF8.GetBytes(serializedCalendar);

            return(File(bytesCalendar, "text/calendar", "kalender.ics"));
        }
Ejemplo n.º 28
0
        public static bool SaveCalendar(Calendar calendar)
        {
            var cs     = new CalendarSerializer(new SerializationContext());
            var result = cs.SerializeToString(calendar);

            File.WriteAllText(Path, result);
            return(true);
        }
Ejemplo n.º 29
0
        public void VTimeZoneEasternStandardTimeShouldSerializeProperly()
        {
            var iCal       = CreateTestCalendar("Eastern Standard Time");
            var serializer = new CalendarSerializer();
            var serialized = serializer.SerializeToString(iCal);

            Assert.IsTrue(serialized.Contains("TZID:Eastern Standard Time"), "Time zone not found in serialization");
        }
Ejemplo n.º 30
0
        public void VTimeZoneAmericaPhoenixShouldSerializeProperly2()
        {
            var iCal       = CreateTestCalendar("America/Phoenix", DateTime.Now, false);
            var serializer = new CalendarSerializer();
            var serialized = serializer.SerializeToString(iCal);

            Assert.IsTrue(serialized.Contains("TZID:America/Phoenix"), "Time zone not found in serialization");
            Assert.IsFalse(serialized.Contains("BEGIN:DAYLIGHT"), "Daylight savings should not exist for Phoenix.");
        }