Ejemplo n.º 1
0
        public CalendarIcalViewModel GenerateIcalBetweenDateRange(DateTime start, DateTime end, string userId)
        {
            // Get user's calendar entries within the date range.
            var userEntries = _scheduleRepository.GetAllUserEvents(userId, start, end);

            // Check if there are any diary entries to sync.
            if (userEntries == null)
            {
                return(null);
            }

            // Create iCal.
            var iCal = new Ical.Net.Calendar()
            {
                ProductId = "ASP.Net Diary Scheduler",
                Version   = "2.0"
            };

            // Create a new event for each calendar entry.
            foreach (CalEventDm entry in userEntries)
            {
                CreateCalendarIcalEventFromCalendarEvent(iCal, entry);
            }

            // Build the .ics file.
            return(CreateCalendarIcalViewModelFromIcal(iCal));
        }
        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.º 3
0
        public CalendarICSDTO CreateEventICS(int eventId, int userId)
        {
            CheckRightsToExport(eventId, userId);

            var @event = _evRepository.GetEvent(eventId);

            var icsEvent = new CalendarEvent
            {
                Summary  = @event.Name,
                Location = @event.Venue,
                Start    = new CalDateTime(@event.StartDateTime),
                End      = new CalDateTime(@event.EndDateTime)
            };

            if (@event.NotificationTime != null)
            {
                icsEvent.Alarms.Add(new Alarm
                {
                    Trigger = new Trigger(TimeSpan.FromMinutes(-(int)@event.NotificationTime))
                });
            }

            var icsCalendar = new Ical.Net.Calendar
            {
                Events = { icsEvent }
            };

            return(new CalendarICSDTO
            {
                ICSContent = new CalendarSerializer(icsCalendar).SerializeToString(),
                CalendarName = @event.Name
            });
        }
Ejemplo n.º 4
0
        public static BaseCalendar ConvertCalendar(Ical.Net.Calendar calandarObj)
        {
            if (calandarObj == null)
            {
                return(null);
            }

            var result = new BusinessObjects.Calendar();

            result.Name = string.IsNullOrEmpty(calandarObj.Name)
                           ? calandarObj.Properties.ContainsKey("X-WR-CALNAME")
                                 ? calandarObj.Properties["X-WR-CALNAME"].Value.ToString()
                                 : string.Empty
                           : calandarObj.Name;

            result.Description = calandarObj.Properties.ContainsKey("X-WR-CALDESC")
                                     ? calandarObj.Properties["X-WR-CALDESC"].Value.ToString()
                                     : string.Empty;

            var tzids = calandarObj.TimeZones.Select(x => x.TzId).Where(x => !string.IsNullOrEmpty(x)).ToList();

            result.TimeZone = tzids.Any()
                                  ? TimeZoneConverter.GetTimeZone(tzids.First())
                                  : (calandarObj.Properties.ContainsKey("X-WR-TIMEZONE")
                                         ? TimeZoneConverter.GetTimeZone(
                                         calandarObj.Properties["X-WR-TIMEZONE"].Value.ToString())
                                         : CoreContext.TenantManager.GetCurrentTenant().TimeZone);

            return(result);
        }
Ejemplo n.º 5
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.º 6
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));
        }
        public static async Task Main(string[] args)
        {
            var calendarUrl = File.ReadAllText(Path.Combine(
                                                   Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                                                   ConfigFileName));

            using var client = new HttpClient();
            var response = await client.GetAsync(calendarUrl);

            if (!response.IsSuccessStatusCode)
            {
                Console.Error.WriteLine(
                    $"Failed to load calendar. Server returned {response.StatusCode}");
                return;
            }

            var time = args.Length > 0 ? DateTime.Parse(args.First()) : DateTime.Now;

            Logger.Log($"Getting events from {time.ToString(CultureInfo.CurrentCulture)}");

            var cal    = Calendar.Load(await response.Content.ReadAsStreamAsync());
            var events = cal.Calendar.GetOccurrences(time, time + TimeSpan.FromDays(1));

            var orderEvents = events
                              .Where(f => !((CalendarEvent)f.Source).IsAllDay)
                              .OrderBy(f => f.Period.StartTime.Value)
                              .ToList();

            Logger.Log(string.Join('\n',
                                   orderEvents.Select(e => $"{e.Period.StartTime.Value}: {((CalendarEvent) e.Source).Summary}")));

            var message = "";

            if (orderEvents.Count > 0)
            {
                // Push out already started events if we have more
                if (orderEvents.Count > 1 &&
                    orderEvents.First().Period.StartTime.Value < (time - TimeSpan.FromMinutes(10)))
                {
                    orderEvents.RemoveAt(0);
                }

                var nextEvent     = (CalendarEvent)orderEvents.First().Source;
                var nextOccurence = orderEvents.First().Period.StartTime;
                message = $"{nextOccurence.Value:HH:mm} {nextEvent.Summary}";
            }
            else
            {
                message = "No events within 24h";
            }

            if (message.Length > 30)
            {
                message = message.Substring(0, 28) + "...";
            }

            Console.WriteLine(
                $"{message} | iconName=view-calendar");
        }
Ejemplo n.º 8
0
 public static string SerializeCalendar(Ical.Net.Calendar calendar)
 {
     try
     {
         var serializer = new Ical.Net.Serialization.CalendarSerializer(calendar);
         return(serializer.SerializeToString(calendar));
     }
     catch (Exception)
     {
         return(null);
     }
 }
        // Create a .ics file for calendar events from a date range.
        public ActionResult ExportEventsToIcal(DateTime start, DateTime end)
        {
            // Check if dates are null before doing anything.
            if (start == null || end == null)
            {
                return(SiteErrorHandler.GetBadRequestActionResult("<strong>Error:</strong> No date range provided.", ""));
            }

            // Get user's calendar entries within the date range.
            List <CalEntry> userEntries = _scheduleRepository.GetAllUserEntries(User.Identity.GetUserId(), start, end);

            // Check if there are any diary entries to sync.
            if (userEntries == null)
            {
                return(SiteErrorHandler.GetBadRequestActionResult("<strong>Error:</strong> No calendar events to sync.", ""));
            }

            // Create iCal.
            var iCal = new Ical.Net.Calendar()
            {
                ProductId = "ASP.Net Diary Scheduler",
                Version   = "2.0"
            };

            // Create a new event for each calendar entry.
            foreach (CalEntry entry in userEntries)
            {
                // Create event.
                var evt = iCal.Create <Ical.Net.CalendarComponents.CalendarEvent>();

                // Prepare ical event.
                evt.Uid         = entry.CalendarEntryId.ToString();
                evt.Start       = new Ical.Net.DataTypes.CalDateTime(entry.DateFrom);
                evt.End         = new Ical.Net.DataTypes.CalDateTime(entry.DateTo);
                evt.Description = entry.Description;
                evt.Summary     = entry.Title;
                evt.IsAllDay    = entry.AllDay;
            }

            // Build the .ics file.
            Ical.Net.Serialization.SerializationContext ctx = new Ical.Net.Serialization.SerializationContext();
            var serialiser = new Ical.Net.Serialization.CalendarSerializer(ctx);

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

            // Create a name.
            Guid   fileId   = Guid.NewGuid();
            string fileName = fileId.ToString() + ".ics";

            return(File(bytes, contentType, fileName));
        }
Ejemplo n.º 10
0
 public static string SerializeCalendar(Ical.Net.Calendar calendar)
 {
     try
     {
         var serializer = new Ical.Net.Serialization.CalendarSerializer();
         return(serializer.SerializeToString(calendar));
     }
     catch (Exception ex)
     {
         LogManager.GetLogger("ASC.Calendar").Error(ex);
         return(null);
     }
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Create a calendar event in the <see cref="Ical.Net.Calendar"/>.
        /// </summary>
        /// <param name="iCal">The calendar to add the event to.</param>
        /// <param name="entry">The event to add.</param>
        private void CreateCalendarIcalEventFromCalendarEvent(Ical.Net.Calendar iCal, CalEventDm entry)
        {
            // Create event.
            var evt = iCal.Create <Ical.Net.CalendarComponents.CalendarEvent>();

            // Prepare ical event.
            evt.Uid         = entry.CalendarEntryId.ToString();
            evt.Start       = new Ical.Net.DataTypes.CalDateTime(entry.DateFrom);
            evt.End         = new Ical.Net.DataTypes.CalDateTime(entry.DateTo);
            evt.Description = entry.Description;
            evt.Summary     = entry.Title;
            evt.IsAllDay    = entry.AllDay;
        }
Ejemplo n.º 12
0
        private string GetCalendarData()
        {
            Ical.Net.Calendar calendar = new Ical.Net.Calendar();
            Ical.Net.Event    calevent = new Ical.Net.Event();
            calevent.DtStart     = new CalDateTime(StartOn);
            calevent.DtEnd       = new CalDateTime(EndOn);
            calevent.Description = Description;
            calevent.Location    = Location;
            calevent.Summary     = Subject;
            calevent.Organizer   = new Organizer(CreatedBy.CorporateEmail);
            calevent.IsAllDay    = AllDay;
            calevent.Uid         = Oid.ToString();

            foreach (ScheduleParticipant peeps in ScheduleParticipants)
            {
                string role;
                switch ((int)peeps.AttendanceType)
                {
                case 0:
                    role = "REQ-PARTICIPANT";
                    break;

                case 1:
                    role = "OPT-PARTICIPANT";
                    break;

                case 2:
                    role = "NON-PARTICIPANT";
                    break;

                default:
                    role = "REQ-PARTICIPANT";
                    break;
                }
                Attendee attendee = new Attendee()
                {
                    CommonName = peeps.Participant.FullName,
                    Role       = role,
                    Rsvp       = true,
                    Value      = new Uri(String.Format("mailto:{0}", peeps.Participant.CorporateEmail))
                };
                calevent.Attendees.Add(attendee);
            }
            calendar.Events.Add(calevent);
            calendar.Method = "REQUEST";
            CalendarSerializer serializer = new CalendarSerializer(calendar);
            string             calData    = serializer.SerializeToString();

            return(calData);
        }
Ejemplo n.º 13
0
        public static string SerializeCalendar(Ical.Net.Calendar calendar)
        {
            try
            {
                var serializer = new Ical.Net.Serialization.CalendarSerializer();

                return(StringUtils.NormalizeStringForMySql(serializer.SerializeToString(calendar)));
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return(null);
            }
        }
Ejemplo n.º 14
0
        public bool Contains(Ical.Net.Calendar calendar)
        {
            if (!History.Any() || calendar == null || calendar.Events == null || calendar.Events.FirstOrDefault() == null)
                return false;

            var eventObj = calendar.Events.First();

            var isExist = History
                .Where(x => x.Method == calendar.Method)
                .Select(x => x.Events.First())
                .Any(x => x.Sequence == eventObj.Sequence && DDayICalParser.ToUtc(x.DtStamp) == DDayICalParser.ToUtc(eventObj.DtStamp));

            return isExist;
        }
Ejemplo n.º 15
0
        /// <summary>
        ///Generate the outputs
        ///
        /// </summary>
        /// <returns> Returns a string that goes to the screen</returns>
        public string OutputEvents(Calendar cal)
        {
            //send it back to be sent by email
            _dbCallsSessionDataDTO.SeatBookingsCalOutputToEmail = cal;

            //send it back to output on the screen
            var sb = new StringBuilder();

            foreach (var email in cal.Events)
            {
                sb.AppendLine("From: " + email.DtStart + " To " + email.DtEnd);
                sb.AppendLine("Desc: " + email.Description + " By " + email.Name);
            }
            return(sb.ToString());
        }
Ejemplo n.º 16
0
        public void EnsureAutomaticallySetDTSTAMPisSerializedAsKindUTC()
        {
            var ical = new Ical.Net.Calendar();
            var evt  = new Ical.Net.Event();

            ical.Events.Add(evt);

            var serializer         = new Ical.Net.Serialization.iCalendar.Serializers.CalendarSerializer();
            var serializedCalendar = serializer.SerializeToString(ical);

            var lines  = serializedCalendar.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();
            var result = lines.First(s => s.StartsWith("DTSTAMP"));

            Assert.AreEqual($"DTSTAMP:{evt.DtStamp.Year}{evt.DtStamp.Month:00}{evt.DtStamp.Day:00}T{evt.DtStamp.Hour:00}{evt.DtStamp.Minute:00}{evt.DtStamp.Second:00}Z", result);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Send the data to the Index page for users to check their booking, need to tie it into the Session numbers
        /// </summary>
        /// <param name="cal"></param>
        /// <returns>Returns a list of data to be looped through on the index page</returns>
        public List <CalendarEvent> OutputEventsToIndex(Calendar cal)
        {
            IOrderedEnumerable <CalendarEvent> orderedCal = cal.Events
                                                            .OrderByDescending(d => d.DtStart)
                                                            .ThenBy(s => s.Class); //session ID

            //send it back to output on the screen
            var sessions = new List <CalendarEvent>();

            //foreach (var email in orderedCal)
            //{
            //    sessions.Add(email.Class + " "+  email.DtStart.Date.ToShortDateString() + " " + email.Description);
            //}

            return(orderedCal.ToList());
        }
Ejemplo n.º 18
0
        private EntityCollection<ExcludeMatchDateEntity> Map(Ical.Net.Calendar iCal, string defaultTimeZoneId, DateTimePeriod dateLimits)
        {
            var excluded = new EntityCollection<ExcludeMatchDateEntity>();
            
            // small come before big date ranges
            foreach (var calendarEvent in iCal.Events.OrderBy(e => e.DtStart.Date).ThenBy(e => e.Duration.Days))
            {
                var exclDate = CreateEntity(calendarEvent, defaultTimeZoneId);
                if (dateLimits.Contains(exclDate.DateFrom) || dateLimits.Contains(exclDate.DateTo))
                {
                    excluded.Add(CreateEntity(calendarEvent, defaultTimeZoneId));
                }
            }

            return excluded;
        }
Ejemplo n.º 19
0
        public void EnsureCorrectSetDTSTAMPisSerializedAsKindUTC()
        {
            var ical = new Ical.Net.Calendar();
            var evt  = new Ical.Net.Event();

            evt.DtStamp = new CalDateTime(new DateTime(2016, 8, 17, 2, 30, 0, DateTimeKind.Utc));
            ical.Events.Add(evt);

            var serializer         = new Ical.Net.Serialization.iCalendar.Serializers.CalendarSerializer();
            var serializedCalendar = serializer.SerializeToString(ical);

            var lines  = serializedCalendar.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();
            var result = lines.First(s => s.StartsWith("DTSTAMP"));

            Assert.AreEqual("DTSTAMP:20160817T023000Z", result);
        }
Ejemplo n.º 20
0
        static void Main(string[] args)
        {
            string login_url = "https://student.racunarstvo.hr/pretinac/main.php";
            string table_url = "https://student.racunarstvo.hr/pretinac/main.php?what=raspored_tjedni&week=next&next=";
            string currWeekHtml, currWeekJson, username, password;

            Console.WriteLine("Infoeducal - Infoeduka iCal format converter\nUsername:"******"Password: "******"")
                {
                    Console.WriteLine("Error reading calendar, bad username/password or server unavailable");
                    Console.ReadKey();
                    Environment.Exit(1);
                }
                var parsedWeek = JsonConvert.DeserializeObject <IEnumerable <Dogadaj> >(currWeekJson).ToList();
                allEvents.AddRange(parsedWeek);
            }

            var calendar = new Calendar();

            for (int i = 0; i < allEvents.Count; i++)
            {
                var dogadaj = calendar.Create <CalendarEvent>();
                dogadaj.Summary = allEvents[i].title;
                dogadaj.Start   = new CalDateTime(DateTime.ParseExact(allEvents[i].start, "yyyy-MM-dd HH:mm",
                                                                      CultureInfo.InvariantCulture));
                dogadaj.End = new CalDateTime(DateTime.ParseExact(allEvents[i].end, "yyyy-MM-dd HH:mm",
                                                                  CultureInfo.InvariantCulture));
            }

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

            System.IO.File.WriteAllText(@"Kalendar_Infoeduka.ics", icalString);
        }
        // Create a .ics file for a calendar event.
        public ActionResult ExportEventToIcal(Guid id)
        {
            // Check if an id was sent.
            if (id == Guid.Empty)
            {
                return(SiteErrorHandler.GetBadRequestActionResult("<strong>Error:</strong> Invalid calendar event id.", ""));
            }

            var entry = _scheduleRepository.GetCalendarEntry(id);

            if (entry == null)
            {
                return(SiteErrorHandler.GetBadRequestActionResult("<strong>Error:</strong> The calendar event could not be found.", ""));
            }

            // Create iCal.
            var iCal = new Ical.Net.Calendar()
            {
                ProductId = "ASP.Net Diary Scheduler",
                Version   = "2.0"
            };

            // Create event.
            var evt = iCal.Create <Ical.Net.CalendarComponents.CalendarEvent>();

            // Prepare ical event.
            evt.Uid         = entry.CalendarEntryId.ToString();
            evt.Start       = new Ical.Net.DataTypes.CalDateTime(entry.DateFrom);
            evt.End         = new Ical.Net.DataTypes.CalDateTime(entry.DateTo);
            evt.Description = entry.Description;
            evt.Summary     = entry.Title;
            evt.IsAllDay    = entry.AllDay;

            // Build the .ics file.
            var ctx        = new Ical.Net.Serialization.SerializationContext();
            var serialiser = new Ical.Net.Serialization.CalendarSerializer(ctx);

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

            // Create a name.
            Guid   fileId   = Guid.NewGuid();
            string fileName = fileId.ToString() + ".ics";

            return(File(bytes, contentType, fileName));
        }
Ejemplo n.º 22
0
        public async Task <IEnumerable <Event> > GetCalendarAsync(int numberOfDays, bool useCache = true)
        {
            if (useCache && _cache.TryGetValue("calendar", out IEnumerable <Event> cachedEvents))
            {
                _logger.LogInformation("[CACHE] Got calendar from cache.");
                return(cachedEvents);
            }

            try
            {
                System.IO.Stream stream = await _httpClient.GetStreamAsync(_calendarConfiguration.CalendarUrl);

                Ical.Net.Calendar calendar = Ical.Net.Calendar.Load(stream);
                IOrderedEnumerable <Ical.Net.CalendarComponents.CalendarEvent> events = calendar.Events
                                                                                        .Where(p => p.DtStart.AsSystemLocal.Date >= DateTime.Now.Date && p.DtStart.AsSystemLocal.Date <= DateTime.Now.AddDays(numberOfDays).Date)
                                                                                        .OrderBy(p => p.DtStart);

                IEnumerable <Event> mappedEvents = events.Select(p => new Event
                {
                    DtStart  = p.DtStart.AsSystemLocal,
                    DtEnd    = p.DtEnd.AsSystemLocal,
                    IsAllDay = p.IsAllDay,
                    Summary  = p.Summary
                });

                if (events != null)
                {
                    _cache.Set("calendar", mappedEvents, new DistributedCacheEntryOptions
                    {
                        AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30)
                    });
                }
                else
                {
                    _logger.LogError("Unable to get calendar, events is null.");
                }

                _logger.LogInformation("Got calendar.");
                return(mappedEvents);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error loading calendar");
                return(null);
            }
        }
        private async Task <Calendar> ScrapeCalendar()
        {
            var context = BrowsingContext.New(Configuration.Default);

            var body = await _httpClient.GetStringAsync("https://sport.tv2.dk/e-sport/2021-02-02-hvornaar-er-der-csgo-paa-zulu");

            var document = await context.OpenAsync(req => req.Content(body));

            var contentDiv = document.QuerySelector("div.tc_richcontent");

            var calendar = new Calendar();

            calendar.AddProperty("X-WR-CALNAME", "CsGo på TV2");
            calendar.AddProperty("X-WR-TIMEZONE", "Europe/Amsterdam");

            var uls        = contentDiv.QuerySelectorAll("ul");
            var dateString = "";

            foreach (var ul in uls)
            {
                var dateEl = ul.PreviousElementSibling.FirstElementChild;
                if (dateEl.TagName == "STRONG")
                {
                    dateString = dateEl.InnerHtml.Split(':').LastOrDefault()?.Replace("D.", "").Trim();
                }

                foreach (var li in ul.Children)
                {
                    var time = li.InnerHtml.Split(":").FirstOrDefault();
                    DateTime.TryParse(dateString + $" {DateTime.Now.Year} {time}", new CultureInfo("da-dk"), DateTimeStyles.None, out var startDate);

                    var name = li.InnerHtml.Replace(time + ":", "").Replace(System.Environment.NewLine, string.Empty).Trim();

                    calendar.Events.Add(new CalendarEvent
                    {
                        Summary = name,
                        DtStart = new CalDateTime(startDate),
                        Start   = new CalDateTime(startDate),
                        DtEnd   = new CalDateTime(startDate.AddHours(1)),
                        End     = new CalDateTime(startDate.AddHours(1)),
                    });
                }
            }

            return(calendar);
        }
Ejemplo n.º 24
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);
            string  calendarId  = req.Query["id"];

            calendarId = calendarId ?? data?.id;

            var cloudTable = await CreateCalendarsTableAsync();

            var calendar = await GetCalendar(cloudTable, calendarId);

            if (calendar == null)
            {
                throw new Exception("Calendar not found");
            }

            Ical.Net.Calendar c;
            Ical.Net.Calendar outc = new Ical.Net.Calendar();
            using (var response = await WebRequest
                                  .Create(calendar.Url)
                                  .GetResponseAsync())

                using (var stream = response.GetResponseStream())
                {
                    c = Ical.Net.Calendar.Load(stream);
                }

            var filter = CalendarFilterFactory.GetFilter(calendar.Filter);

            foreach (var e in c.Events)
            {
                if (filter.IsMatch(e))
                {
                    outc.Events.Add(e);
                }
            }

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

            return((ActionResult) new OkObjectResult(serializedCalendar));
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Create the <see cref="CalendarIcalViewModel"/> using the <see cref="Ical.Net.Calendar"/>.
        /// </summary>
        /// <param name="iCal">The calendar to generate an ics from.</param>
        /// <returns>THe <see cref="CalendarIcalViewModel"/> holding the ics data.</returns>
        private CalendarIcalViewModel CreateCalendarIcalViewModelFromIcal(Ical.Net.Calendar iCal)
        {
            var fileData = new CalendarIcalViewModel();

            Ical.Net.Serialization.SerializationContext ctx = new Ical.Net.Serialization.SerializationContext();
            var serialiser = new Ical.Net.Serialization.CalendarSerializer(ctx);

            string output = serialiser.SerializeToString(iCal);

            fileData.ContentType = "text/calendar";
            fileData.Data        = System.Text.Encoding.UTF8.GetBytes(output);

            // Create a name.
            Guid fileId = Guid.NewGuid();

            fileData.FileName = fileId.ToString() + ".ics";
            return(fileData);
        }
Ejemplo n.º 26
0
        /* public BaseCalendar ConvertCalendar(Ical.Net.Calendar calandarObj)
         * {
         *   if (calandarObj == null) return null;
         *
         *   var icalendar = new iCalendar(AuthContext, TimeZoneConverter, TenantManager);
         *   var result = new BusinessObjects.Calendar(AuthContext, TimeZoneConverter, icalendar, DataProvider);
         *
         *   result.Name = string.IsNullOrEmpty(calandarObj.Name)
         *                  ? calandarObj.Properties.ContainsKey("X-WR-CALNAME")
         *                        ? calandarObj.Properties["X-WR-CALNAME"].Value.ToString()
         *                        : string.Empty
         *                  : calandarObj.Name;
         *
         *   result.Description = calandarObj.Properties.ContainsKey("X-WR-CALDESC")
         *                            ? calandarObj.Properties["X-WR-CALDESC"].Value.ToString()
         *                            : string.Empty;
         *
         *   var tzids = calandarObj.TimeZones.Select(x => x.TzId).Where(x => !string.IsNullOrEmpty(x)).ToList();
         *
         *   result.TimeZone = tzids.Any()
         *                         ? TimeZoneConverter.GetTimeZone(tzids.First())
         *                         : (calandarObj.Properties.ContainsKey("X-WR-TIMEZONE")
         *                                ? TimeZoneConverter.GetTimeZone(
         *                                    calandarObj.Properties["X-WR-TIMEZONE"].Value.ToString())
         *                                : TimeZoneConverter.GetTimeZone(TenantManager.GetCurrentTenant().TimeZone));
         *
         *   return result;
         * }*/

        public Ical.Net.Calendar ConvertCalendar(BaseCalendar calandarObj)
        {
            if (calandarObj == null)
            {
                return(null);
            }

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

            result.Method    = Ical.Net.CalendarMethods.Publish;
            result.Scale     = Ical.Net.CalendarScales.Gregorian;
            result.Version   = Ical.Net.LibraryMetadata.Version;
            result.ProductId = "-//Ascensio System//OnlyOffice Calendar//EN";

            if (!string.IsNullOrEmpty(calandarObj.Name))
            {
                result.AddProperty("X-WR-CALNAME", calandarObj.Name);
            }

            if (!string.IsNullOrEmpty(calandarObj.Description))
            {
                result.AddProperty("X-WR-CALDESC", calandarObj.Description);
            }

            if (calandarObj.TimeZone == null)
            {
                calandarObj.TimeZone = TimeZoneConverter.GetTimeZone(TenantManager.GetCurrentTenant().TimeZone);
            }

            var olsonTzId = TimeZoneConverter.WindowsTzId2OlsonTzId(calandarObj.TimeZone.Id);
            var olsonTz   = olsonTzId == calandarObj.TimeZone.Id
                              ? calandarObj.TimeZone
                              : TimeZoneInfo.CreateCustomTimeZone(olsonTzId,
                                                                  calandarObj.TimeZone.GetOffset(true),
                                                                  calandarObj.TimeZone.DisplayName,
                                                                  calandarObj.TimeZone.StandardName);

            result.AddTimeZone(Ical.Net.CalendarComponents.VTimeZone.FromSystemTimeZone(olsonTz));
            result.AddProperty("X-WR-TIMEZONE", olsonTzId);

            return(result);
        }
Ejemplo n.º 27
0
        public CalendarICSDTO CreateEventSeriesICS(int eventId, int userId)
        {
            CheckRightsToExport(eventId, userId);

            var @event = _evRepository.GetEvent(eventId);

            if (@event.SeriesId == null)
            {
                throw new NotFoundException("Not event series");
            }

            var eventSeries = _evRepository.GetSeries(@event.SeriesId.Value);

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

            icsCalendar.Events.AddRange(eventSeries.Select(evt =>
            {
                var icsEvent = new CalendarEvent
                {
                    Summary  = evt.Name,
                    Location = evt.Venue,
                    Start    = new CalDateTime(evt.StartDateTime),
                    End      = new CalDateTime(evt.EndDateTime)
                };

                if (evt.NotificationTime != null)
                {
                    icsEvent.Alarms.Add(new Alarm
                    {
                        Trigger = new Trigger(TimeSpan.FromMinutes(-(int)evt.NotificationTime))
                    });
                }

                return(icsEvent);
            }));

            return(new CalendarICSDTO
            {
                ICSContent = new CalendarSerializer(icsCalendar).SerializeToString(),
                CalendarName = @event.Name
            });
        }
Ejemplo n.º 28
0
        public void ProcessEvents(Calendar vCal, DiscordSocketClient discord, MasterDivisionRegistry mdr)
        {
            foreach (var calEvt in vCal.Events.OrderBy(x => x.Start.Ticks))
            {
                DIEvent evt = null;

                if (Events.Any(x => x.UID == calEvt.Uid))
                {
                    evt = Events.First(x => x.UID == calEvt.Uid);

                    var description = DIEvent.DetailsRegex.Match(calEvt.Description).Groups[1].Value.Replace("\n\n", "\n").Trim();
                    if (description == string.Empty)
                    {
                        description = calEvt.Description.Replace("\n\n", "\n").Trim();
                    }

                    if (evt.Start != calEvt.DtStart.AsUtc ||
                        evt.End != (calEvt.DtEnd?.AsUtc ?? DateTime.MinValue.ToUniversalTime()) ||
                        evt.RawTitle != calEvt.Summary ||
                        evt.Description != description)
                    {
                        evt.CopyFrom(calEvt);

                        ProcessTriggers(evt, discord, mdr, true);
                    }

                    continue;
                }

                evt = new DIEvent();

                evt.CopyFrom(calEvt);

                Events.Add(evt);

                if (evt.End > DateTime.UtcNow)
                {
                    ProcessTriggers(evt, discord, mdr);
                }
            }
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://sports.yahoo.com/nfl/teams/cin/ical.ics");

            myRequest.Method = "GET";
            WebResponse myResponse = myRequest.GetResponseAsync().Result;

            using (StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8))
            {
                Ical.Net.Calendar calendar = Ical.Net.Calendar.Load(sr.ReadToEnd());
                foreach (var events in calendar.Events)
                {
                    EventList.Add(new Events()
                    {
                        Datetime = events.DtStart.ToString("dd-MM hh:mm", null), Summary = events.Summary
                    });
                }
            }
        }
Ejemplo n.º 30
0
        public CalendarIcalViewModel GenerateIcalForCalendarEvent(Guid id)
        {
            var entry = _scheduleRepository.GetCalendarEvent(id);

            if (entry == null)
            {
                return(null);
            }

            // Create iCal.
            var iCal = new Ical.Net.Calendar()
            {
                ProductId = "ASP.Net Diary Scheduler",
                Version   = "2.0"
            };

            // Create event.
            CreateCalendarIcalEventFromCalendarEvent(iCal, entry);

            // Build the .ics file.
            return(CreateCalendarIcalViewModelFromIcal(iCal));
        }