public void Add2Attendees() { var evt = VEventFactory(); Assert.AreEqual(0, evt.Attendees.Count); evt.Attendees.Add(_attendees[0]); evt.Attendees.Add(_attendees[1]); Assert.AreEqual(2, evt.Attendees.Count); Assert.AreEqual(ParticipationRole.RequiredParticipant, evt.Attendees[1].Role); var cal = new Calendar(); cal.Events.Add(evt); var serializer = new CalendarSerializer(); Console.Write(serializer.SerializeToString(cal)); }
public void VTimeZoneAmericaEirunepeShouldSerializeProperly() { var iCal = CreateTestCalendar("America/Eirunepe"); var serializer = new CalendarSerializer(); var serialized = serializer.SerializeToString(iCal); Assert.IsTrue(serialized.Contains("TZID:America/Eirunepe"), "Time zone not found in serialization"); Assert.IsTrue(serialized.Contains("BEGIN:STANDARD"), "The standard timezone info was not serialized"); Assert.IsTrue(serialized.Contains("BEGIN:DAYLIGHT"), "The daylight timezone info was not serialized"); Assert.IsTrue(serialized.Contains("TZNAME:-04"), "-04 was not serialized"); Assert.IsTrue(serialized.Contains("TZNAME:-05"), "-05 was not serialized"); Assert.IsTrue(serialized.Contains("DTSTART:19311003T110000"), "DTSTART:19311003T110000 was not serialized"); Assert.IsTrue(serialized.Contains("DTSTART:19320401T000000"), "DTSTART:19320401T000000 was not serialized"); Assert.IsTrue(serialized.Contains("DTSTART:20080624T000000"), "DTSTART:20080624T000000 was not serialized"); Assert.IsTrue(serialized.Contains("DTSTART:19501201T000000"), "DTSTART:19501201T000000 was not serialized"); // Should not contain the following Assert.IsFalse(serialized.Contains("RDATE:19501201T000000/P1D"), "The RDATE was not serialized correctly, should be RDATE:19501201T000000"); }
public async Task <IActionResult> Calendar(Guid id) { var calendar = await _schoolingEventService.GenerateCalendar(id); if (IsValidOperation()) { var serializer = new CalendarSerializer(calendar); var serializedCalendar = serializer.SerializeToString(); var calendarBytes = Encoding.ASCII.GetBytes(serializedCalendar); return(File(calendarBytes, "application/octet-stream", $"{id}_calendar.iCal")); } return(BadRequest(new { success = false, errors = _notifications.GetNotifications().Select(n => n.Value) })); }
public void AttendeesSerialized() { //ToDo: This test is broken as of 2016-07-13 var cal = new Calendar { Method = "REQUEST", Version = "2.0" }; var evt = AttendeeTest.VEventFactory(); cal.Events.Add(evt); const string org = "MAILTO:[email protected]"; evt.Organizer = new Organizer(org); evt.Attendees.AddRange(_attendees); // However a bug, when a participation value is changed, ultimately re-serialises as an array (PARTSTAT=ACCEPTED,DECLINED) evt.Attendees[0].ParticipationStatus = EventParticipationStatus.Declined; var serializer = new CalendarSerializer(); var serializedCalendar = serializer.SerializeToString(cal); var vEvt = InspectSerializedSection(serializedCalendar, "VEVENT", new[] { "ORGANIZER:" + org }); foreach (var a in evt.Attendees) { var vals = GetValues(vEvt, "ATTENDEE", a.Value.OriginalString); foreach (var v in new Dictionary <string, string> { ["CN"] = a.CommonName, ["ROLE"] = a.Role, ["RSVP"] = a.Rsvp.ToString() .ToUpperInvariant(), ["PARTSTAT"] = a.ParticipationStatus }) { Assert.IsTrue(vals.ContainsKey(v.Key), $"could not find key '{v.Key}'"); Assert.AreEqual(v.Value, vals[v.Key], $"ATENDEE prop '{v.Key}' differ"); } } }
public void LineColumns2() { var ctx = new SerializationContext(); var settings = ctx.GetService(typeof(ISerializationSettings)) as ISerializationSettings; settings.EnsureAccurateLineNumbers = true; var serializer = new CalendarSerializer { SerializationContext = ctx }; var iCal = Calendar.LoadFromStream(new StringReader(IcsFiles.Calendar1), serializer)[0]; Assert.IsNotNull(iCal.Todos["2df60496-1e73-11db-ba96-e3cfe6793b5f"]); Assert.IsNotNull(iCal.Todos["4836c236-1e75-11db-835f-a024e2a6131f"]); Assert.AreEqual(110, iCal.Todos["4836c236-1e75-11db-835f-a024e2a6131f"].Properties["LOCATION"].Line); Assert.AreEqual(123, iCal.Todos["2df60496-1e73-11db-ba96-e3cfe6793b5f"].Properties["UID"].Line); }
public virtual ActionResult Calendar() { var calendar = new Calendar(); FT_ManagementContext context = HttpContext.RequestServices.GetService(typeof(FT_ManagementContext)) as FT_ManagementContext; List <Ferias> LstFerias = context.ObterListaFeriasValidadas(DateTime.Parse(DateTime.Now.Year + "-01-01"), DateTime.Parse(DateTime.Now.Year + "-12-31")); foreach (var f in LstFerias) { var e = new CalendarEvent { Start = new CalDateTime(f.DataInicio), End = new CalDateTime(f.DataFim.AddDays(1)), IsAllDay = true, Uid = f.Id.ToString(), Description = "Validado por: " + f.ValidadoPorNome + "\r\nObservações: " + f.Obs, Summary = "Férias - " + context.ObterUtilizador(f.IdUtilizador).NomeCompleto, LastModified = new CalDateTime(DateTime.Now) }; calendar.Events.Add(e); } var serializer = new CalendarSerializer(); var serializedCalendar = serializer.SerializeToString(calendar); var bytesCalendar = new UTF8Encoding(false).GetBytes(serializedCalendar); MemoryStream ms = new MemoryStream(bytesCalendar); ms.Write(bytesCalendar, 0, bytesCalendar.Length); ms.Position = 0; var cd = new System.Net.Mime.ContentDisposition { FileName = "Ferias.ics", Inline = false, Size = bytesCalendar.Length, CreationDate = DateTime.Now }; Response.Headers.Add("Content-Disposition", cd.ToString()); return(File(ms, "text/calendar")); }
/// <summary> /// Gets the ical appoinment. /// </summary> /// <param name="model">The model.</param> /// <param name="guid">The unique identifier.</param> /// <param name="sequence">The sequence.</param> /// <returns></returns> /// <inheritdoc /> public ICalAppointmentModel GetICalAppoinment( AppointmentModel model, string guid = null, int sequence = 0) { Event calendarEvent = new Event { DtStart = new CalDateTime(model.StartTime), DtEnd = new CalDateTime(model.StartTime.AddMinutes(model.Duration)), Description = model.Description, Summary = model.Description, Organizer = new Organizer(model.CreatedUser), Status = GetStatus(model.Status), Location = model.Location, Attendees = GetAttendees(model.Attendees) }; if (guid != null) { calendarEvent.Uid = guid; } calendarEvent.Sequence = sequence; Calendar calendar = new Calendar(); calendar.Events.Add(calendarEvent); CalendarSerializer serializer = new CalendarSerializer(new SerializationContext()); string serializedCalendar = serializer.SerializeToString(calendar); //// according to the Ical spec Status should be in uppercase! serializedCalendar = serializedCalendar.Replace("STATUS:Confirmed", "STATUS:CONFIRMED"); serializedCalendar = serializedCalendar.Replace("STATUS:Cancelled", "STATUS:CANCELLED"); return(new ICalAppointmentModel { Guid = calendarEvent.Uid, SerializedString = serializedCalendar, ContentType = GetContentType(model.Status), Sequence = calendarEvent.Sequence }); }
private void ToIcsFileButton_Click(object sender, EventArgs e) { String icsFileName; //ics文件名 var courses = new List <Course>(); //课程列表 var calendar = new Calendar(); //日历相关 var serializer = new CalendarSerializer(); var serializedCalendar = serializer.SerializeToString(calendar); var termStrat = new DateTime(); //学期开始日 string icsPath; //ics文件完整目录 try { //得到ics文件名并且获得课程列表 icsFileName = XlsToCourse(courses, XlsFilePath.Text); //判断开始日是否是星期一并生成学期开始日期 if (dateTimePicker1.Value.DayOfWeek != DayOfWeek.Monday) { throw new Exception(NotMondayMessage); } termStrat = new DateTime(dateTimePicker1.Value.Year, dateTimePicker1.Value.Month, dateTimePicker1.Value.Day, 0, 0, 0); CourseToIcs(courses, calendar, termStrat); serializer = new CalendarSerializer(); serializedCalendar = serializer.SerializeToString(calendar); icsPath = Path.Combine(Path.GetDirectoryName(xlsFilePathString), icsFileName + ".ics"); File.WriteAllText(icsPath, serializedCalendar); MessageBox.Show("成功生成文件"); } catch (Exception ex) { if (ex.Message.CompareTo(NotMondayMessage) == 0) { MessageBox.Show(NotMondayMessage); } else { MessageBox.Show(FileErrorMessage); } } }
public static void SendAppointment(DateTime startDate, DateTime endDate, string toEmail, string fromEmail, string password) { SmtpClient client = new SmtpClient(); client.Port = 587; client.Host = "smtp.office365.com"; client.EnableSsl = true; client.Timeout = 10000; client.DeliveryMethod = SmtpDeliveryMethod.Network; client.UseDefaultCredentials = false; client.Credentials = new System.Net.NetworkCredential(fromEmail, password); MailMessage message = new MailMessage(); message.To.Add(toEmail); message.From = new MailAddress(fromEmail); message.Subject = "Upcoming Court Date"; message.Body = "Here's your upcoming court date"; message.IsBodyHtml = true; var calendar = new Calendar(); var iEvent = calendar.Create <CalendarEvent>(); iEvent.Summary = "Court Hearing"; iEvent.Start = new CalDateTime(startDate); iEvent.End = new CalDateTime(endDate); iEvent.Description = "Court Hearing Appointment"; iEvent.Status = EventStatus.Confirmed; iEvent.Location = "County Court House"; calendar.Events.Add(iEvent); var serializer = new CalendarSerializer(); var serializedCalendar = serializer.SerializeToString(calendar); var bytesCalendar = Encoding.UTF8.GetBytes(serializedCalendar); MemoryStream ms = new MemoryStream(bytesCalendar); System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(ms, "event.ics", "text/calendar"); message.Attachments.Add(attachment); client.Send(message); }
public void VTimeZoneAmericaAnchorageShouldSerializeProperly() { var iCal = CreateTestCalendar("America/Anchorage"); var serializer = new CalendarSerializer(); var serialized = serializer.SerializeToString(iCal); Assert.IsTrue(serialized.Contains("TZID:America/Anchorage"), "Time zone not found in serialization"); Assert.IsTrue(serialized.Contains("BEGIN:STANDARD"), "The standard timezone info was not serialized"); Assert.IsTrue(serialized.Contains("BEGIN:DAYLIGHT"), "The daylight timezone info was not serialized"); Assert.IsTrue(serialized.Contains("TZNAME:AHST"), "AHST was not serialized"); Assert.IsTrue(serialized.Contains("TZNAME:AHDT"), "AHDT was not serialized"); Assert.IsTrue(serialized.Contains("TZNAME:AKST"), "AKST was not serialized"); Assert.IsTrue(serialized.Contains("TZNAME:YST"), "YST was not serialized"); Assert.IsTrue(serialized.Contains("TZNAME:AHDT"), "AHDT was not serialized"); Assert.IsTrue(serialized.Contains("TZNAME:LMT"), "LMT was not serialized"); Assert.IsTrue(serialized.Contains("RDATE:19731028T020000"), "RDATE:19731028T020000 was not serialized"); Assert.IsTrue(serialized.Contains("RDATE:19801026T020000"), "RDATE:19801026T020000 was not serialized"); Assert.IsTrue(serialized.Contains("DTSTART:19420209T020000"), "DTSTART:19420209T020000 was not serialized"); Assert.IsFalse(serialized.Contains("RDATE:19670401/P1D"), "RDate was not properly serialized for vtimezone, should be RDATE:19670401T000000"); }
public void Schedule_UpdatedWithSpecificDates_EffectiveEndDateIsLastSpecifiedDate() { // Create a daily recurring calendar that has an end date of today +3 months. var scheduleEndDate = RockDateTime.Now.AddMonths(3); var schedule = ScheduleTestHelper.GetScheduleWithDailyRecurrence(endDate: scheduleEndDate, eventDuration: null); Assert.That.AreEqualDate(scheduleEndDate, schedule.EffectiveEndDate); // Modify the Schedule to use a set of discrete dates and verify that the EffectiveEndDate is adjusted correctly. var serializer = new CalendarSerializer(_calendarSpecificDates); schedule.iCalendarContent = serializer.SerializeToString(); schedule.EnsureEffectiveStartEndDates(); var specificEndDate = _specificDates.Last(); Assert.That.AreEqualDate(specificEndDate, schedule.EffectiveEndDate); }
public void TimeZoneSerialize() { //ToDo: This test is broken as of 2016-07-13 var cal = new Calendar { Method = "PUBLISH", Version = "2.0" }; const string exampleTz = "New Zealand Standard Time"; var tzi = TimeZoneInfo.FindSystemTimeZoneById(exampleTz); var timezone = VTimeZone.FromSystemTimeZone(tzi); cal.AddTimeZone(timezone); var evt = new Event { Summary = "Testing", Start = new CalDateTime(2016, 7, 14, timezone.TzId), End = new CalDateTime(2016, 7, 15, timezone.TzId) }; cal.Events.Add(evt); var serializer = new CalendarSerializer(new SerializationContext()); var serializedCalendar = serializer.SerializeToString(cal); Console.Write(serializedCalendar); var vTimezone = InspectSerializedSection(serializedCalendar, "VTIMEZONE", new[] { "TZID:" + timezone.TzId }); var o = tzi.BaseUtcOffset.ToString("hhmm", CultureInfo.InvariantCulture); InspectSerializedSection(vTimezone, "STANDARD", new[] { "TZNAME:" + tzi.StandardName, "TZOFFSETTO:" + o //todo - standard time, for NZ standard time (current example) //"DTSTART:20150402T030000", //"RRULE:FREQ=YEARLY;BYDAY=1SU;BYHOUR=3;BYMINUTE=0;BYMONTH=4", //"TZOFFSETFROM:+1300" }); InspectSerializedSection(vTimezone, "DAYLIGHT", new[] { "TZNAME:" + tzi.DaylightName, "TZOFFSETFROM:" + o }); }
public void VTimeZoneAmericaLosAngelesShouldSerializeProperly() { var iCal = CreateTestCalendar("America/Los_Angeles"); var serializer = new CalendarSerializer(); var serialized = serializer.SerializeToString(iCal); Assert.IsTrue(serialized.Contains("TZID:America/Los_Angeles"), "Time zone not found in serialization"); Assert.IsTrue(serialized.Contains("BEGIN:STANDARD"), "The standard timezone info was not serialized"); Assert.IsTrue(serialized.Contains("BEGIN:DAYLIGHT"), "The daylight timezone info was not serialized"); Assert.IsTrue(serialized.Contains("BYDAY=2SU"), "BYDAY=2SU was not serialized"); Assert.IsTrue(serialized.Contains("TZNAME:PDT"), "PDT was not serialized"); Assert.IsTrue(serialized.Contains("TZNAME:PST"), "PST was not serialized"); Assert.IsTrue(serialized.Contains("TZNAME:PPT"), "PPT was not serialized"); Assert.IsTrue(serialized.Contains("TZNAME:PWT"), "PWT was not serialized"); Assert.IsTrue(serialized.Contains("DTSTART:19180331T020000"), "DTSTART:19180331T020000 was not serialized"); Assert.IsTrue(serialized.Contains("DTSTART:20071104T020000"), "DTSTART:20071104T020000 was not serialized"); Assert.IsTrue(serialized.Contains("DTSTART:20070311T020000"), "DTSTART:20070311T020000 was not serialized"); //Assert.IsTrue(serialized.Contains("TZURL:http://tzurl.org/zoneinfo/America/Los_Angeles"), "TZURL:http://tzurl.org/zoneinfo/America/Los_Angeles was not serialized"); //Assert.IsTrue(serialized.Contains("RDATE:19600424T010000"), "RDATE:19600424T010000 was not serialized"); // NodaTime doesn't match with what tzurl has }
public void VTimeZoneAmericaChicagoShouldSerializeProperly() { var iCal = CreateTestCalendar("America/Chicago"); var serializer = new CalendarSerializer(); var serialized = serializer.SerializeToString(iCal); Assert.IsTrue(serialized.Contains("TZID:America/Chicago"), "Time zone not found in serialization"); Assert.IsTrue(serialized.Contains("BEGIN:STANDARD"), "The standard timezone info was not serialized"); Assert.IsTrue(serialized.Contains("BEGIN:DAYLIGHT"), "The daylight timezone info was not serialized"); Assert.IsTrue(serialized.Contains("TZNAME:CDT"), "CDT was not serialized"); Assert.IsTrue(serialized.Contains("TZNAME:CST"), "CST was not serialized"); Assert.IsTrue(serialized.Contains("TZNAME:EST"), "EST was not serialized"); Assert.IsTrue(serialized.Contains("TZNAME:CWT"), "CWT was not serialized"); Assert.IsTrue(serialized.Contains("TZNAME:CPT"), "CPT was not serialized"); Assert.IsTrue(serialized.Contains("DTSTART:19181027T020000"), "DTSTART:19181027T020000 was not serialized"); Assert.IsTrue(serialized.Contains("DTSTART:19450814T180000"), "DTSTART:19450814T180000 was not serialized"); Assert.IsTrue(serialized.Contains("DTSTART:19420209T020000"), "DTSTART:19420209T020000 was not serialized"); Assert.IsTrue(serialized.Contains("DTSTART:19360301T020000"), "DTSTART:19360301T020000 was not serialized"); Assert.IsTrue(serialized.Contains("DTSTART:20070311T020000"), "DTSTART:20070311T020000 was not serialized"); Assert.IsTrue(serialized.Contains("DTSTART:20071104T020000"), "DTSTART:20071104T020000 was not serialized"); }
public string GetCalendar(Guid rosterId, string initials, int daysPriorToCommence = 14) { var calendar = new Calendar { Version = CalendarVersions.Latest, Method = CalendarMethods.Publish }; var staffMember = _context.Staff.Include("Department") .Single(s => s.RosterId == rosterId && s.StaffMemberCode == initials); staffMember.LastViewedVersionId = _context.Versions.Max(v => v.Number); foreach (var e in GetCalls(staffMember, daysPriorToCommence)) { calendar.Events.Add(e); } _context.SaveChanges(); var serializer = new CalendarSerializer(new SerializationContext()); return(serializer.SerializeToString(calendar)); }
public void VTimeZoneEuropeMoscowShouldSerializeProperly() { var iCal = CreateTestCalendar("Europe/Moscow"); var serializer = new CalendarSerializer(); var serialized = serializer.SerializeToString(iCal); Assert.IsTrue(serialized.Contains("TZID:Europe/Moscow"), "Time zone not found in serialization"); Assert.IsTrue(serialized.Contains("BEGIN:STANDARD"), "The standard timezone info was not serialized"); Assert.IsTrue(serialized.Contains("BEGIN:DAYLIGHT"), "The daylight timezone info was not serialized"); Assert.IsTrue(serialized.Contains("TZNAME:MSD"), "MSD was not serialized"); Assert.IsTrue(serialized.Contains("TZNAME:MSK"), "MSK info was not serialized"); Assert.IsTrue(serialized.Contains("TZNAME:MSD"), "MSD was not serialized"); Assert.IsTrue(serialized.Contains("TZNAME:MST"), "MST was not serialized"); Assert.IsTrue(serialized.Contains("TZNAME:MMT"), "MMT was not serialized"); Assert.IsTrue(serialized.Contains("TZOFFSETFROM:+023017"), "TZOFFSETFROM:+023017 was not serialized"); Assert.IsTrue(serialized.Contains("TZOFFSETTO:+023017"), "TZOFFSETTO:+023017 was not serialized"); Assert.IsTrue(serialized.Contains("DTSTART:19180916T010000"), "DTSTART:19180916T010000 was not serialized"); Assert.IsTrue(serialized.Contains("DTSTART:19171228T000000"), "DTSTART:19171228T000000 was not serialized"); Assert.IsTrue(serialized.Contains("RDATE:19991031T030000"), "RDATE:19991031T030000 was not serialized"); }
public async Task <ActionResult <string> > GetAsync() { HttpClient client = new HttpClient(); client.BaseAddress = new Uri("https://api.data.gov.sg/v1/environment/"); HttpResponseMessage response = await client.GetAsync("4-day-weather-forecast"); ForecastWrapper fList = null; if (response.IsSuccessStatusCode) { var json = await response.Content.ReadAsStringAsync(); fList = JsonConvert.DeserializeObject <ForecastWrapper>(json); } if (fList == null) { return(null); } var calendar = new Calendar(); foreach (var forecast in fList.items.First().forecasts) { var e = new CalendarEvent { IsAllDay = true, Start = new CalDateTime(forecast.date), End = new CalDateTime(forecast.date), Summary = forecast.forecast }; calendar.Events.Add(e); } var serializer = new CalendarSerializer(); return(serializer.SerializeToString(calendar)); }
public async Task <IActionResult> Calendar(Guid uniqueId, int character) { var filter = new BsonDocument("_id", character); var accessToken = new MongoContext().Database.GetCollection <AccessTokenModel>("AccessToken").FindSync <AccessTokenModel>(filter).FirstOrDefault(); if (accessToken == null || !accessToken.UniqueId.Equals(uniqueId)) { return(new JsonResult(new { Error = "incorrect accesstoken" })); } if (DateTime.Now > accessToken.ExpiryDate) { accessToken = await authorizationService.RefreshToken(accessToken); } var events = await calendarService.GetMails(accessToken); Calendar calendar = new Calendar(); calendar.ProductId = "-//Running With Dogs//Calender esi 1.0//EN"; calendar.Version = "1.0"; calendar.AddTimeZone(TimeZoneInfo.Utc); calendar.Events.AddRange(events.Select(x => { CalendarEvent cevent = new CalendarEvent(); cevent.Start = new CalDateTime(x.Date.Value); cevent.End = new CalDateTime(x.Date.Value.AddMinutes(x.Duration.Value)); cevent.Priority = x.Importance.Value; cevent.Summary = x.Title; cevent.Description = x.Text; return(cevent); })); var serializer = new CalendarSerializer(); var serializedCalendar = serializer.SerializeToString(calendar); return(Content(serializedCalendar, "text/calendar;charset=UTF-8")); }
static void Main(string[] args) { var clHelper = new CineListHelper.CineListHelper(); clHelper.OnTrivialError += (sender, message) => { Console.WriteLine(message); }; clHelper.OnInformationalMessage += (sender, message) => { Console.WriteLine("INFO: " + message); }; var cFactory = new CalendarFactory(); try { var cinemaListings = clHelper.GetLocalMovies("G731JN", 10).Result; var cal = cFactory.Convert(cinemaListings); //cal.TimeZones.Add(new Ical.Net.CalendarComponents.VTimeZone("Europe/London")); //cal.TimeZones.Add(new Ical.Net.CalendarComponents.VTimeZone("GMT")); //cal.Name = "CinemaList Calendar"; //cal.Version = "4.0"; if (cal != null) { File.Delete("./calendar.ical"); var calSerializer = new CalendarSerializer(); var calString = calSerializer.SerializeToString(cal); using (var writer = new StreamWriter("./calendar.ical")) { writer.Write(calString); } } } catch (System.Net.Http.HttpRequestException e) { Console.WriteLine(e.Message); } }
/// <summary> /// Processes the request. /// </summary> /// <param name="httpContext">The HTTP context.</param> public void ProcessRequest(HttpContext httpContext) { try { request = httpContext.Request; response = httpContext.Response; interactionDeviceType = InteractionDeviceType.GetClientType(request.UserAgent); if (!ValidateSecurity(httpContext)) { return; } RockContext rockContext = new RockContext(); CalendarProps calendarProps = ValidateRequestData(httpContext); if (calendarProps == null) { return; } var icalendar = CreateICalendar(calendarProps); var serializer = new CalendarSerializer(); string s = serializer.SerializeToString(icalendar); response.Clear(); response.ClearHeaders(); response.ClearContent(); response.AddHeader("content-disposition", string.Format("attachment; filename={0}_ical.ics", RockDateTime.Now.ToString("yyyy-MM-dd_hhmmss"))); response.ContentType = "text/calendar"; response.Write(s); } catch (Exception ex) { ExceptionLogService.LogException(ex, httpContext); SendBadRequest(httpContext); } }
public async Task <string> GetCalendarAsync(SubjectOptions[] options, string facultyId, string groupId) { var page = await _client.GetClassesPageAsync(facultyId, groupId); var classes = ClassParser.Parse(page, groupId); var calendarEvents = new List <CalendarEvent>(); foreach (var c in classes) { if (!options.Any(x => x.Title == c.Title)) { continue; } if (c.Subgroup != null && !options.Where(x => x.Title == c.Title).Any(x => x.Subgroups.Contains((int)c.Subgroup))) { continue; } calendarEvents.Add(new CalendarEvent { End = new CalDateTime(c.End, "Europe/Vilnius"), Start = new CalDateTime(c.Start, "Europe/Vilnius"), Summary = c.Title, Location = c.Location, Description = $"{c.Teacher}\n{c.Type}{(c.Subgroup != null ? $"\nPogrupis {c.Subgroup}" : $"")}" }); } var calendar = new Calendar(); calendar.Events.AddRange(calendarEvents); var serializer = new CalendarSerializer(); return(serializer.SerializeToString(calendar)); }
public async Task Run([TimerTrigger("0 0 6 * * *" #if DEBUG , RunOnStartup = true #endif )] TimerInfo myTimer, ILogger log, ExecutionContext context) //[Blob("$web/output.ics", FileAccess.Write)] Stream icsOutputBlob) - https://github.com/Azure/azure-functions-host/issues/3804 { log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}"); var config = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); var localTz = DateTimeZoneProviders.Tzdb[config.GetValue <string>("LocalTimezone")]; var today = _clock.GetCurrentInstant().InZone(localTz).Date; var pastDate = today.PlusMonths(0 - MONTHS_INTO_PAST); var start = localTz.AtStrictly(new LocalDateTime(pastDate.Year, pastDate.Month, 1, 0, 0, 0)).ToInstant(); var end = localTz.AtStrictly(new LocalDateTime(today.Year + YEARS_INTO_FUTURE, 12, 31, 23, 59, 59)).ToInstant(); var requestUri = new Uri(config.GetValue <string>("SourceUrl")); var sourceEvents = await GetSourceEvents(requestUri, start, end); RecalculateAllDayTimes(sourceEvents); var calendar = MakeCalendar(config, sourceEvents, localTz, requestUri.Host); var serializer = new CalendarSerializer(); var serializedCalendar = serializer.SerializeToString(calendar); var blobReference = await GetCloudBlockBlob(config); await blobReference.UploadTextAsync(serializedCalendar); }
public void Save() { logger.Info("Saving Calendars to: {0}", Path); lock (_fileLock) { File.Copy(Path, PathTools.ChangeExtension(Path, ".ics-backup"), true); var serializer = new CalendarSerializer(new SerializationContext()); using (var file = ZipFile.Open(Path, ZipArchiveMode.Create)) { foreach (var c in _calendars) { var f = file.CreateEntry(c.Key.ToLower()); using (var s = f.Open()) { serializer.Serialize(c.Value, s, CalendarEncoding); } } } _lastSaved = DateTime.Now; Saved = true; } }
public IHttpActionResult Get() { IHttpActionResult response; HttpResponseMessage responseMessage = new HttpResponseMessage(HttpStatusCode.OK); var e = new CalendarEvent { Start = new CalDateTime(DateTime.Now), End = new CalDateTime(DateTime.Now.AddHours(1)), Location = "Eric's Cube", Description = "Chillin at Eric's cube. who you with? me and my peeps why you bring 4 of your friiiiiieeeends." }; var calendar = new Calendar(); calendar.Events.Add(e); var serializer = new CalendarSerializer(); var serializedCalendar = serializer.SerializeToString(calendar); byte[] calendarBytes = System.Text.Encoding.UTF8.GetBytes(serializedCalendar); //iCal is the calendar string responseMessage.Content = new ByteArrayContent(calendarBytes); responseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("text/calendar"); response = ResponseMessage(responseMessage); return(response); }
public string GetIcsText(Event eventItem, string currentUrl) { var startDateWithTime = GetCombinedDateAndTime(eventItem.EventDate, eventItem.StartTime); var endDateWithTime = GetCombinedDateAndTime(eventItem.EventDate, eventItem.EndTime); var e = new CalendarEvent() { Name = "VEVENT", Summary = eventItem.Title, DtStart = new CalDateTime(startDateWithTime), DtEnd = new CalDateTime(endDateWithTime), Location = eventItem.Location, Description = "For details, link here: " + currentUrl }; var calendar = new Calendar(); calendar.Events.Add(e); var serializer = new CalendarSerializer(new SerializationContext()); return(serializer.SerializeToString(calendar)); }
public byte[] GenerateICSFile(EventDTO eventDto) { var calendar = new Calendar(); calendar.Events.Add(new CalendarEvent { Class = "PUBLIC", Summary = eventDto.Name + " - " + eventDto.Description, Created = new CalDateTime(DateTime.Now), //Description = dto.Detail, Start = new CalDateTime(eventDto.TimeStart.Value), End = new CalDateTime(eventDto.TimeStop.Value), Sequence = 0, Uid = Guid.NewGuid().ToString(), Location = eventDto.Address + " " + eventDto.City + " " + eventDto.State + " " + eventDto.Zip, }); var serializer = new CalendarSerializer(); var serializedCalendar = serializer.SerializeToString(calendar); byte[] calendarBytes = System.Text.Encoding.UTF8.GetBytes(serializedCalendar); return(calendarBytes); }
public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "HttpTriggerCSharp/IcsMerge/{calendar}")] HttpRequestMessage req, string calendar, TraceWriter log) { log.Info("C# HTTP trigger function processed a request."); //URL to where JSON files are located //TODO: Extend this to allow other storage locations (ex. database, rest service, etc) //TODO: Proper error handeling if file does not exist string blobBaseUrl = ConfigurationManager.AppSettings["AzureBlobStorgageBaseUrl"]; Uri jsonFileUrl = new Uri(new Uri(blobBaseUrl), calendar + ".json"); string icsMergeJson = DownloadFileToString(jsonFileUrl); IcsMergeDetails mergeDetails = JsonConvert.DeserializeObject <IcsMergeDetails>(icsMergeJson); //Combine all calendars Calendar combinedCalendar = new Calendar(); foreach (string calendarUrl in mergeDetails.calendars) { string calendarToCombineString = DownloadFileToString(new Uri(calendarUrl)); Calendar calednarToCombine = Calendar.Load(calendarToCombineString); combinedCalendar.MergeWith(calednarToCombine); } CalendarSerializer serializer = new CalendarSerializer(); string serializedCombinedCalendar = serializer.SerializeToString(combinedCalendar); //Return combined calednar as file HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); result.Content = new ByteArrayContent(System.Text.Encoding.UTF8.GetBytes(serializedCombinedCalendar)); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = calendar + ".ics" }; result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); return(result); }
public void AttachmentFormatType() { var cal1 = new Calendar { Events = { new CalendarEvent { Attachments = { new Attachment(Encoding.UTF8.GetBytes("{}")) { FormatType = "application/json", }, }, }, }, }; var serializer = new CalendarSerializer(); var serializedCalendar = serializer.SerializeToString(cal1); var cal2 = Calendar.Load(serializedCalendar); Assert.AreEqual("application/json", cal2.Events.Single().Attachments.Single().FormatType); }
public static IEnumerable <ITestCaseData> EnsureAutomaticallySetDtStampIsSerializedAsUtcKind_TestCases() { var emptyCalendar = new Calendar(); var evt = new CalendarEvent(); emptyCalendar.Events.Add(evt); var serializer = new CalendarSerializer(); yield return(new TestCaseData(serializer.SerializeToString(emptyCalendar)) .SetName("Empty calendar with empty event returns true") .Returns(true)); var explicitDtStampCalendar = new Calendar(); var explicitDtStampEvent = new CalendarEvent { DtStamp = new CalDateTime(new DateTime(2016, 8, 17, 2, 30, 0, DateTimeKind.Utc)) }; explicitDtStampCalendar.Events.Add(explicitDtStampEvent); yield return(new TestCaseData(serializer.SerializeToString(explicitDtStampCalendar)) .SetName("CalendarEvent with explicitly-set DTSTAMP property returns true") .Returns(true)); }
public void PropertySerialization_Tests() { const string formatted = @"FMTTYPE=text/html:<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 3.2//EN"">\n<HTML>\n<HEAD>\n<META NAME=""Generator"" CONTENT=""MS Exchange Server version rmj.rmm.rup.rpr"">\n<TITLE></TITLE>\n</HEAD>\n<BODY>\n<!-- Converted from text/rtf format -->\n\n<P DIR=LTR><SPAN LANG=""en-us""><FONT FACE=""Calibri"">This is some</FONT></SPAN><SPAN LANG=""en-us""><B> <FONT FACE=""Calibri"">HTML</FONT></B></SPAN><SPAN LANG=""en-us""><FONT FACE=""Calibri""></FONT></SPAN><SPAN LANG=""en-us""><U> <FONT FACE=""Calibri"">formatted</FONT></U></SPAN><SPAN LANG=""en-us""><FONT FACE=""Calibri""></FONT></SPAN><SPAN LANG=""en-us""><I> <FONT FACE=""Calibri"">text</FONT></I></SPAN><SPAN LANG=""en-us""><FONT FACE=""Calibri"">.</FONT></SPAN><SPAN LANG=""en-us""></SPAN></P>\n\n</BODY>\n</HTML>"; var start = DateTime.Now; var end = start.AddHours(1); var @event = new CalendarEvent { Start = new CalDateTime(start), End = new CalDateTime(end), Description = "This is a description", }; var property = new CalendarProperty("X-ALT-DESC", formatted); @event.AddProperty(property); var calendar = new Calendar(); calendar.Events.Add(@event); var serialized = new CalendarSerializer().SerializeToString(calendar); Assert.IsTrue(serialized.Contains("X-ALT-DESC;")); }