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);
        }
Beispiel #2
0
        public async Task SendInvitationAsync(EventJoinValidationDto @event, IEnumerable <string> userIds, int orgId)
        {
            var emails = await _usersDbSet
                         .Where(u => userIds.Contains(u.Id))
                         .Select(u => u.Email)
                         .ToListAsync();

            var calendarEvent = MapToCalendarEvent(@event);

            await AddEventLinkToDescriptionAsync(calendarEvent, @event.Id, orgId);

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

            calendar.Events.Add(calendarEvent);

            var serializedCalendar = new CalendarSerializer().SerializeToString(calendar);
            var calByteArray       = Encoding.UTF8.GetBytes(serializedCalendar);
            var emailDto           = new EmailDto(emails, $"Invitation: {@event.Name} @ {@event.StartDate.ToString("d")}", "");

            using (var stream = new MemoryStream(calByteArray))
            {
                emailDto.Attachment = new MailAttachment(stream, "invite.ics");
                await _mailingService.SendEmailAsync(emailDto);
            }
        }
Beispiel #3
0
        public async Task <byte[]> DownloadEventAsync(Guid eventId, int orgId)
        {
            var @event = await _eventsDbSet.FindAsync(eventId);

            _eventValidationService.CheckIfEventExists(@event);

            var calEvent = new CalendarEvent
            {
                // ReSharper disable once PossibleNullReferenceException
                Uid         = @event.Id.ToString(),
                Location    = @event.Place,
                Summary     = @event.Name,
                Description = @event.Description,
                Organizer   = new Organizer {
                    CommonName = BusinessLayerConstants.EmailSenderName, Value = new Uri($"mailto:{BusinessLayerConstants.FromEmailAddress}")
                },
                Start  = new CalDateTime(@event.StartDate, "UTC"),
                End    = new CalDateTime(@event.EndDate, "UTC"),
                Status = EventStatus.Confirmed
            };

            await AddEventLinkToDescriptionAsync(calEvent, eventId, orgId);

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

            cal.Events.Add(calEvent);
            var serializedCalendar = new CalendarSerializer().SerializeToString(cal);
            var calByteArray       = Encoding.UTF8.GetBytes(serializedCalendar);

            return(calByteArray);
        }
Beispiel #4
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"));
        }
Beispiel #5
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 async Task <IReadOnlyCollection <IGCalEventSyncOperation> > GetEventSyncOperations(
            string gCalID, iCal.Calendar iCal)
        {
            var iCalEvents = iCal.Events
                             .ToDictionary(e => e.Uid, e => new iCalEvent(e));
            var gCalEvents = (await gCalService.ReadEvents(gCalID))
                             .ToDictionary(e => e.ICalUID, e => new GCalEvent(e));
            var operations = new List <IGCalEventSyncOperation>();

            operations.AddRange(
                from @event in iCalEvents.Values
                where !gCalEvents.ContainsKey(@event.Uid)
                select new ImportGCalEventOperation(@event, gCalID));

            operations.AddRange(
                from iCalEvent in iCalEvents.Values
                where gCalEvents.ContainsKey(iCalEvent.Uid)
                let gCalEvent = gCalEvents[iCalEvent.Uid]
                                where iCalEvent.HasChanges(gCalEvent)
                                select new UpdateGCalEventOperation(iCalEvent, gCalEvent, gCalID));

            operations.AddRange(
                from @event in gCalEvents.Values
                where !iCalEvents.ContainsKey(@event.Uid)
                select new DeleteGCalEventOperation(@event, gCalID));

            return(operations.OrderBy(o => o.Priority).ToArray());
        }
Beispiel #7
0
        private void CreateEvent(Ical.Net.Calendar calendar, Movie movie, bool cinemasRelease)
        {
            var date = cinemasRelease ? movie.InCinemas : movie.PhysicalRelease;

            if (!date.HasValue)
            {
                return;
            }

            var occurrence = calendar.Create <CalendarEvent>();

            occurrence.Uid    = "NzbDrone_movie_" + movie.Id + (cinemasRelease ? "_cinemas" : "_physical");
            occurrence.Status = movie.Status == MovieStatusType.Announced ? EventStatus.Tentative : EventStatus.Confirmed;

            occurrence.Start    = new CalDateTime(date.Value);
            occurrence.End      = occurrence.Start;
            occurrence.IsAllDay = true;

            occurrence.Description = movie.Overview;
            occurrence.Categories  = new List <string>()
            {
                movie.Studio
            };

            var physicalText = "(Physical Release)";

            occurrence.Summary = $"{movie.Title} " + (cinemasRelease ? "(Theatrical Release)" : physicalText);
        }
Beispiel #8
0
        public async Task <IActionResult> ExportICal(string calendarItemId)
        {
            CalendarItem calendarItem = await repository.GetDocument(calendarItemId);

            if (calendarItem == null)
            {
                return(new NotFoundResult());
            }
            string description = calendarItem.PlainDescription ?? calendarItem.Summary ?? String.Empty;

            if (!String.IsNullOrEmpty(calendarItem.UrlTitle))
            {
                description += " https://robert-brands.com/termine/" + calendarItem.UrlTitle;
            }
            CalendarEvent e = new CalendarEvent
            {
                Start       = new CalDateTime(calendarItem.StartDate),
                End         = new CalDateTime(calendarItem.EndDate),
                Summary     = calendarItem.Title,
                Description = description,
                Location    = calendarItem.Place,
                IsAllDay    = calendarItem.WholeDay,
                Organizer   = new Organizer(calendarItem.Host)
            };

            Ical.Net.Calendar calendar = new Ical.Net.Calendar();
            calendar.Events.Add(e);

            var    serializer = new Ical.Net.Serialization.CalendarSerializer();
            string iCal       = serializer.SerializeToString(calendar);

            return(File(new System.Text.UTF8Encoding().GetBytes(iCal), "text/calendar", "iCal.ics"));
        }
        private async Task <Ical.Net.Calendar> GetCalendarAsync(string href)
        {
            Ical.Net.Calendar calendar = null;
            string            calendarName;
            string            readAll = "";

            try
            {
                // получу конкретный календарь personal
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(href);
                request.Credentials = new NetworkCredential("*****@*****.**", "!QAZ3edc");
                request.ContentType = "text/xml";
                request.Headers.Add("Depth", "0");
                request.Headers.Add("If-None-Match", "*");
                request.Method = "GET";
                request.ServerCertificateValidationCallback = delegate { return(true); }; // при публикации на боевой сервер убрать
                HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync();

                using (Stream stream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        readAll  = reader.ReadToEnd();
                        calendar = Ical.Net.Calendar.Load(readAll);
                    }
                }
                response.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            return(calendar);
        }
Beispiel #10
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);
        }
Beispiel #11
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            var calendar = new Ical.Net.Calendar();

            calendar.Method = CalendarMethods.Publish; // Outlook needs this property "REQUEST" will update an existing event with the same UID (Unique ID) and a newer time stamp.
            CalendarEvent e = new CalendarEvent()
            {
                Class     = "Public",
                Organizer = new Organizer()
                {
                    CommonName = "Eric Vandekerckhove", Value = new Uri("mailto:[email protected]")
                },
                Summary     = "Summary here",
                Created     = new CalDateTime(DateTime.Now),
                Description = "Description here",
                Start       = new CalDateTime(DateTime.ParseExact("15/10/2018 15:00", "dd/MM/yyyy HH:mm", null)),
                End         = new CalDateTime(DateTime.ParseExact("15/10/2018 16:00", "dd/MM/yyyy HH:mm", null)),
                Sequence    = 0,
                Uid         = Guid.NewGuid().ToString(),
                Location    = "Here"
            };

            //https://tools.ietf.org/html/rfc5545#page-25
            //"ROLE" "="
            //("CHAIR"            ; Indicates chair of the calendar entity
            // "REQ-PARTICIPANT"  ; Indicates a participant whose participation is required
            // "OPT-PARTICIPANT"  ; Indicates a participant whose participation is optional
            // "NON-PARTICIPANT"  ; Indicates a participant who is copied for information purposes only
            // x-name             ; Experimental role
            // iana-token)        ; Other IANA role
            // Default is REQ-PARTICIPANT

            e.Attendees.Add(new Attendee()
            {
                CommonName          = "Veerle Serneels",
                ParticipationStatus = "REQ-PARTICIPANT",
                Rsvp  = true,
                Value = new Uri("mailto:[email protected]")
            });

            Alarm alarm = new Alarm()
            {
                Action  = AlarmAction.Display,
                Trigger = new Trigger(TimeSpan.FromDays(-1)),
                Summary = "Meeting in 1 day"
            };

            e.Alarms.Add(alarm);

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

            Console.WriteLine(serializedCalendar);
        }
Beispiel #12
0
        private static byte[] GetIcsContent(CalendarEvent icsEvent)
        {
            var calendar = new Ical.Net.Calendar
            {
                Events = { icsEvent }
            };
            var    serializer = new CalendarSerializer();
            string content    = serializer.SerializeToString(calendar);

            return(Encoding.UTF8.GetBytes(content));
        }
        public string Serialize()
        {
            // create calendar, Outlook will ignore the name
            var calendar = new Ical.Net.Calendar
            {
                Name = INLOOX_DISPLAY_NAME
            };

            foreach (var item in _items)
            {
                // check if task item has dates
                if (item.HasStartDate == true &&
                    item.HasEndDate == true)
                {
                    // add basic info
                    var calendarItem = new CalendarEvent
                    {
                        Summary    = item.Name,
                        Start      = new CalDateTime(((DateTimeOffset)item.StartDateTime).UtcDateTime, TIMEZONE_UTC),
                        End        = new CalDateTime(((DateTimeOffset)item.EndDateTime).UtcDateTime, TIMEZONE_UTC),
                        Categories = new List <string> {
                            INLOOX_DISPLAY_NAME, TASK_ENTITY_DISPLAY_NAME, item.PlanningReservationId.ToString()
                        },
                        Uid         = item.PlanningReservationId.ToString(),
                        Description = string.Empty
                    };

                    // add free/busy type
                    calendarItem.AddProperty(STANDARD_FREE_KEY, FREE_VALUE);
                    calendarItem.AddProperty(MICROSOFT_FREE_KEY, FREE_VALUE);

                    // add alarm, Outlook does not support this
                    var alarm = new Alarm()
                    {
                        Summary = item.Name,
                        Trigger = new Trigger(_reminderTimespan),
                        Action  = AlarmAction.Display
                    };
                    calendarItem.Alarms.Add(alarm);

                    // add to calendar
                    calendar.Events.Add(calendarItem);
                }
            }

            // create ICS output
            var serializer         = new CalendarSerializer();
            var serializedCalendar = serializer.SerializeToString(calendar);

            return(serializedCalendar);
        }
Beispiel #14
0
        public IActionResult GetCalendarFeed(int pastDays = 7, int futureDays = 28, string tagList = "", bool unmonitored = false)
        {
            var start = DateTime.Today.AddDays(-pastDays);
            var end   = DateTime.Today.AddDays(futureDays);
            var tags  = new List <int>();

            if (tagList.IsNotNullOrWhiteSpace())
            {
                tags.AddRange(tagList.Split(',').Select(_tagService.GetTag).Select(t => t.Id));
            }

            var books    = _bookService.BooksBetweenDates(start, end, unmonitored);
            var calendar = new Ical.Net.Calendar
            {
                ProductId = "-//readarr.com//Readarr//EN"
            };

            var calendarName = "Readarr Book Schedule";

            calendar.AddProperty(new CalendarProperty("NAME", calendarName));
            calendar.AddProperty(new CalendarProperty("X-WR-CALNAME", calendarName));

            foreach (var book in books.OrderBy(v => v.ReleaseDate.Value))
            {
                var author = _authorService.GetAuthor(book.AuthorId); // Temp fix TODO: Figure out why Book.Author is not populated during BooksBetweenDates Query

                if (tags.Any() && tags.None(author.Tags.Contains))
                {
                    continue;
                }

                var occurrence = calendar.Create <CalendarEvent>();
                occurrence.Uid = "Readarr_book_" + book.Id;

                //occurrence.Status = book.HasFile ? EventStatus.Confirmed : EventStatus.Tentative;
                occurrence.Description = book.Editions.Value.Single(x => x.Monitored).Overview;
                occurrence.Categories  = book.Genres;

                occurrence.Start = new CalDateTime(book.ReleaseDate.Value.ToLocalTime())
                {
                    HasTime = false
                };

                occurrence.Summary = $"{author.Name} - {book.Title}";
            }

            var serializer = (IStringSerializer) new SerializerFactory().Build(calendar.GetType(), new SerializationContext());
            var icalendar  = serializer.SerializeToString(calendar);

            return(Content(icalendar, "text/calendar"));
        }
Beispiel #15
0
        public string GetAsICalFormat(IEnumerable <Event> events, string calendarName, string calenderDescription)
        {
            var calendar = new Calendar {
                Method     = "PUBLISH",
                TimeZones  = { new VTimeZone("Europe/Amsterdam") },
                Properties =
                {
                    new CalendarProperty("X-PUBLISHED-TTL", "PT15M"),
                    new CalendarProperty("X-WR-TIMEZONE",   "Europe/Amsterdam"),
                    new CalendarProperty("X-WR-CALNAME",    calendarName),
                    new CalendarProperty("X-WR-CALDESC",    calenderDescription),
                }
            };

            calendar.AddTimeZone("Europe/Amsterdam");


            foreach (var @event in events.Where(x => x.Start.DateTime != null && x.End.DateTime != null))
            {
                if ([email protected] || [email protected])
                {
                    continue;
                }
                calendar.Events.Add(new CalendarEvent
                {
                    Description = @event.Description,
                    Summary     = @event.Summary,
                    Location    = @event.Location,
                    Attendees   = @event.Attendees == null
                        ? new List <Attendee>()
                        : @event.Attendees.Select(x => new Attendee {
                        CommonName = x.DisplayName, Value = new Uri($"mailto:{x.Email}")
                    }).ToList(),
                    Organizer = @event.Organizer == null
                        ? null
                        : new Organizer {
                        CommonName = @event.Organizer.DisplayName, Value = new Uri($"mailto:{@event.Organizer.Email}"), SentBy = new Uri($"mailto:{@event.Organizer.Email}")
                    },
                    Start = new CalDateTime(@event.Start.DateTime.Value),
                    End   = new CalDateTime(@event.End.DateTime.Value),
                });
            }

            var serializer = new CalendarSerializer();

            return(serializer.SerializeToString(calendar));
        }
Beispiel #16
0
        private void CreateEvent(Ical.Net.Calendar calendar, Movie movie, string releaseType)
        {
            var    date        = movie.InCinemas;
            string eventType   = "_cinemas";
            string summaryText = "(Theatrical Release)";

            if (releaseType == "digital")
            {
                date        = movie.DigitalRelease;
                eventType   = "_digital";
                summaryText = "(Digital Release)";
            }
            else if (releaseType == "physical")
            {
                date        = movie.PhysicalRelease;
                eventType   = "_physical";
                summaryText = "(Physical Release)";
            }

            if (!date.HasValue)
            {
                return;
            }

            var occurrence = calendar.Create <CalendarEvent>();

            occurrence.Uid    = "Radarr_movie_" + movie.Id + eventType;
            occurrence.Status = movie.Status == MovieStatusType.Announced ? EventStatus.Tentative : EventStatus.Confirmed;

            occurrence.Start    = new CalDateTime(date.Value);
            occurrence.End      = occurrence.Start;
            occurrence.IsAllDay = true;

            occurrence.Description = movie.Overview;
            occurrence.Categories  = new List <string>()
            {
                movie.Studio
            };

            occurrence.Summary = $"{movie.Title} " + summaryText;
        }
Beispiel #17
0
        public IActionResult GetCalendarFeed(int pastDays = 7, int futureDays = 28, string tagList = "", bool unmonitored = false)
        {
            var start = DateTime.Today.AddDays(-pastDays);
            var end   = DateTime.Today.AddDays(futureDays);
            var tags  = new List <int>();

            if (tagList.IsNotNullOrWhiteSpace())
            {
                tags.AddRange(tagList.Split(',').Select(_tagService.GetTag).Select(t => t.Id));
            }

            var movies   = _movieService.GetMoviesBetweenDates(start, end, unmonitored);
            var calendar = new Ical.Net.Calendar
            {
                ProductId = "-//radarr.video//Radarr//EN"
            };

            var calendarName = "Radarr Movies Calendar";

            calendar.AddProperty(new CalendarProperty("NAME", calendarName));
            calendar.AddProperty(new CalendarProperty("X-WR-CALNAME", calendarName));

            foreach (var movie in movies.OrderBy(v => v.Added))
            {
                if (tags.Any() && tags.None(movie.Tags.Contains))
                {
                    continue;
                }

                CreateEvent(calendar, movie, "cinematic");
                CreateEvent(calendar, movie, "digital");
                CreateEvent(calendar, movie, "physical");
            }

            var serializer = (IStringSerializer) new SerializerFactory().Build(calendar.GetType(), new SerializationContext());
            var icalendar  = serializer.SerializeToString(calendar);

            return(Content(icalendar, "text/calendar"));
        }
Beispiel #18
0
 public CalendarWrapper()
 {
     Calendar = new Ical.Net.Calendar();
 }
Beispiel #19
0
        private Response GetCalendarFeed()
        {
            var pastDays    = 7;
            var futureDays  = 28;
            var start       = DateTime.Today.AddDays(-pastDays);
            var end         = DateTime.Today.AddDays(futureDays);
            var unmonitored = false;
            //var premiersOnly = false;
            var tags = new List <int>();

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

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

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

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

            if (queryUnmonitored.HasValue)
            {
                unmonitored = bool.Parse(queryUnmonitored.Value);
            }

            //if (queryPremiersOnly.HasValue)
            //{
            //    premiersOnly = bool.Parse(queryPremiersOnly.Value);
            //}

            if (queryTags.HasValue)
            {
                var tagInput = (string)queryTags.Value.ToString();
                tags.AddRange(tagInput.Split(',').Select(_tagService.GetTag).Select(t => t.Id));
            }

            var movies   = _movieService.GetMoviesBetweenDates(start, end, unmonitored);
            var calendar = new Ical.Net.Calendar
            {
                ProductId = "-//radarr.video//Bonarr//EN"
            };

            foreach (var movie in movies.OrderBy(v => v.Added))
            {
                if (tags.Any() && tags.None(movie.Tags.Contains))
                {
                    continue;
                }

                var occurrence = calendar.Create <Event>();
                occurrence.Uid    = "NzbDrone_movie_" + movie.Id;
                occurrence.Status = movie.HasFile ? EventStatus.Confirmed : EventStatus.Tentative;

                switch (movie.Status)
                {
                case MovieStatusType.PreDB:
                    if (movie.PhysicalRelease != null)
                    {
                        occurrence.Start = new CalDateTime(movie.PhysicalRelease.Value)
                        {
                            HasTime = true
                        };
                        occurrence.End = new CalDateTime(movie.PhysicalRelease.Value.AddMinutes(movie.Runtime))
                        {
                            HasTime = true
                        };
                    }
                    break;

                case MovieStatusType.InCinemas:
                    if (movie.InCinemas != null)
                    {
                        occurrence.Start = new CalDateTime(movie.InCinemas.Value)
                        {
                            HasTime = true
                        };
                        occurrence.End = new CalDateTime(movie.InCinemas.Value.AddMinutes(movie.Runtime))
                        {
                            HasTime = true
                        };
                    }
                    break;

                case MovieStatusType.Announced:
                    continue;     // no date

                default:
                    if (movie.PhysicalRelease != null)
                    {
                        occurrence.Start = new CalDateTime(movie.PhysicalRelease.Value)
                        {
                            HasTime = true
                        };
                        occurrence.End = new CalDateTime(movie.PhysicalRelease.Value.AddMinutes(movie.Runtime))
                        {
                            HasTime = true
                        };
                    }
                    break;
                }

                occurrence.Description = movie.Overview;
                occurrence.Categories  = new List <string>()
                {
                    movie.Studio
                };

                occurrence.Summary = $"{movie.Title}";
            }

            var serializer = (IStringSerializer) new SerializerFactory().Build(calendar.GetType(), new SerializationContext());
            var icalendar  = serializer.SerializeToString(calendar);

            return(new TextResponse(icalendar, "text/calendar"));
        }
Beispiel #20
0
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        try
        {
            if (!FileUpload1.HasFile)
            {
                throw new MyFlightbookException("Please provide a file.");
            }

            using (Calendar ic = new Calendar())
            {
                using (CSVReader cr = new CSVReader(FileUpload1.FileContent))
                {
                    string[] rgCols = cr.GetCSVLine(true);

                    int iColSubject   = -1;
                    int iColStartDate = -1;
                    int iColStartTime = -1;
                    int iColEndDate   = -1;
                    int iColEndTime   = -1;
                    int iColLocation  = -1;

                    for (int i = 0; i < rgCols.Length; i++)
                    {
                        switch (rgCols[i])
                        {
                        case "Subject":
                            iColSubject = i;
                            break;

                        case "Start Date":
                            iColStartDate = i;
                            break;

                        case "Start Time":
                            iColStartTime = i;
                            break;

                        case "End Date":
                            iColEndDate = i;
                            break;

                        case "End Time":
                            iColEndTime = i;
                            break;

                        case "Location":
                            iColLocation = i;
                            break;
                        }
                    }

                    if (iColSubject < 0)
                    {
                        throw new MyFlightbookException("No subject column found");
                    }
                    if (iColStartDate < 0)
                    {
                        throw new MyFlightbookException("No start date column found");
                    }
                    if (iColStartTime < 0)
                    {
                        throw new MyFlightbookException("No start time column found");
                    }
                    if (iColEndDate < 0)
                    {
                        throw new MyFlightbookException("No end date column found");
                    }
                    if (iColEndTime < 0)
                    {
                        throw new MyFlightbookException("No end time column found");
                    }
                    if (iColLocation < 0)
                    {
                        throw new MyFlightbookException("No location column found");
                    }

                    int id = 0;
                    while ((rgCols = cr.GetCSVLine()) != null)
                    {
                        if (String.IsNullOrEmpty(rgCols[iColSubject]))
                        {
                            continue;
                        }

                        Event ev = ic.Create <Event>();
                        ev.Uid         = id++.ToString(System.Globalization.CultureInfo.InvariantCulture);
                        ev.IsAllDay    = false;
                        ev.Description = ev.Summary = rgCols[iColSubject];
                        ev.Location    = rgCols[iColLocation];

                        DateTime dtStart = Convert.ToDateTime(String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0} {1}", rgCols[iColStartDate], rgCols[iColStartTime]), System.Globalization.CultureInfo.CurrentCulture);
                        DateTime dtEnd   = Convert.ToDateTime(String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0} {1}", rgCols[iColEndDate], rgCols[iColEndTime]), System.Globalization.CultureInfo.CurrentCulture);
                        ev.Start = new CalDateTime(dtStart, "Pacific Standard Time");
                        ev.End   = new CalDateTime(dtEnd, "Pacific Standard Time");

                        Alarm a = new Alarm();
                        a.Action           = AlarmAction.Display;
                        a.Description      = ev.Summary;
                        a.Trigger          = new Trigger();
                        a.Trigger.DateTime = ev.Start.AddMinutes(-30);
                        ev.Alarms.Add(a);

                        ic.Method = "PUBLISH";
                    }

                    CalendarSerializer s = new CalendarSerializer();

                    string output = s.SerializeToString(ic);
                    Page.Response.Clear();
                    Page.Response.ContentType = "text/calendar";
                    Response.AddHeader("Content-Disposition", String.Format(System.Globalization.CultureInfo.InvariantCulture, "inline;filename={0}.ics", txtTitle.Text));
                    Response.Write(output);
                    Response.Flush();
                    Response.End();
                }
            }
        }
        catch (CSVReaderInvalidCSVException ex)
        {
            lblErr.Text = ex.Message;
        }
        catch (MyFlightbookException ex)
        {
            lblErr.Text = ex.Message;
        }
    }
Beispiel #21
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="calendar">calendar to convert</param>
 public Converter(ical.Calendar calendar) : this()
 {
     Calendar = calendar;
 }
Beispiel #22
0
        private Response GetCalendarFeed()
        {
            var pastDays     = 7;
            var futureDays   = 28;
            var start        = DateTime.Today.AddDays(-pastDays);
            var end          = DateTime.Today.AddDays(futureDays);
            var unmonitored  = false;
            var premiersOnly = false;
            var asAllDay     = false;
            var tags         = new List <int>();

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

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

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

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

            if (queryUnmonitored.HasValue)
            {
                unmonitored = bool.Parse(queryUnmonitored.Value);
            }

            if (queryPremiersOnly.HasValue)
            {
                premiersOnly = bool.Parse(queryPremiersOnly.Value);
            }

            if (queryAsAllDay.HasValue)
            {
                asAllDay = bool.Parse(queryAsAllDay.Value);
            }

            if (queryTags.HasValue)
            {
                var tagInput = (string)queryTags.Value.ToString();
                tags.AddRange(tagInput.Split(',').Select(_tagService.GetTag).Select(t => t.Id));
            }

            var episodes = _episodeService.EpisodesBetweenDates(start, end, unmonitored);
            var calendar = new Ical.Net.Calendar
            {
                ProductId = "-//sonarr.tv//Sonarr//EN"
            };



            foreach (var episode in episodes.OrderBy(v => v.AirDateUtc.Value))
            {
                if (premiersOnly && (episode.SeasonNumber == 0 || episode.EpisodeNumber != 1))
                {
                    continue;
                }

                if (tags.Any() && tags.None(episode.Series.Tags.Contains))
                {
                    continue;
                }

                var occurrence = calendar.Create <Event>();
                occurrence.Uid         = "NzbDrone_episode_" + episode.Id;
                occurrence.Status      = episode.HasFile ? EventStatus.Confirmed : EventStatus.Tentative;
                occurrence.Description = episode.Overview;
                occurrence.Categories  = new List <string>()
                {
                    episode.Series.Network
                };

                if (asAllDay)
                {
                    occurrence.Start = new CalDateTime(episode.AirDateUtc.Value)
                    {
                        HasTime = false
                    };
                }
                else
                {
                    occurrence.Start = new CalDateTime(episode.AirDateUtc.Value)
                    {
                        HasTime = true
                    };
                    occurrence.End = new CalDateTime(episode.AirDateUtc.Value.AddMinutes(episode.Series.Runtime))
                    {
                        HasTime = true
                    };
                }

                switch (episode.Series.SeriesType)
                {
                case SeriesTypes.Daily:
                    occurrence.Summary = $"{episode.Series.Title} - {episode.Title}";
                    break;

                default:
                    occurrence.Summary = $"{episode.Series.Title} - {episode.SeasonNumber}x{episode.EpisodeNumber:00} - {episode.Title}";
                    break;
                }
            }

            var serializer = (IStringSerializer) new SerializerFactory().Build(calendar.GetType(), new SerializationContext());
            var icalendar  = serializer.SerializeToString(calendar);

            return(new TextResponse(icalendar, "text/calendar"));
        }
Beispiel #23
0
        public Calendar ParseICalendar(string source)
        {
            var cleanedSource = Regex.Replace(Regex.Replace(source.Replace("\r", "\n"), "\\n+", "\n"), "\\n(?:([^A-Z]))", "$1");

            return(Calendar.Load(cleanedSource));
        }
Beispiel #24
0
        public void CreateICS(CalEvent calEvent)
        {
            Ical.Net.Calendar calendar = new Ical.Net.Calendar
            {
                Method    = "REQUEST",
                Version   = "2.0",
                ProductId = "SOFO Invitation"
            };

            CalendarEvent calendarEvent = new CalendarEvent
            {
                Uid     = calEvent.ICalUId,
                DtStart = new CalDateTime(calEvent.Start.DateTime.Year, calEvent.Start.DateTime.Month, calEvent.Start.DateTime.Day, calEvent.Start.DateTime.Hour, calEvent.Start.DateTime.Minute, calEvent.Start.DateTime.Second, calEvent.Start.TimeZone), //Start = new CalDateTime(now),
                DtEnd   = new CalDateTime(calEvent.End.DateTime.Year, calEvent.End.DateTime.Month, calEvent.End.DateTime.Day, calEvent.End.DateTime.Hour, calEvent.End.DateTime.Minute, calEvent.End.DateTime.Second, calEvent.End.TimeZone),               //End = new CalDateTime(later),
                //DtStamp = new CalDateTime(calEvent.Start.DateTime.Year, calEvent.Start.DateTime.Month, calEvent.Start.DateTime.Day, calEvent.Start.DateTime.Hour, calEvent.Start.DateTime.Minute, calEvent.Start.DateTime.Second, calEvent.Start.TimeZone),
                IsAllDay = calEvent.IsAllDay,
                //Sequence = 0,
                //Class = "PUBLIC",
                //Priority = calEvent.Importance,
                //Transparency = TransparencyType.Transparent,
                Location    = calEvent.Location.DisplayName,
                Summary     = calEvent.Subject,
                Description = calEvent.BodyPreview,
            };

            Ical.Net.DataTypes.Organizer organizer = new Ical.Net.DataTypes.Organizer();
            organizer.CommonName    = calEvent.Organizer.EmailAddress.Name.ToString();
            organizer.Value         = new Uri($"mailto:{calEvent.Organizer.EmailAddress.Address.ToString()}");
            calendarEvent.Organizer = organizer;

            //Repeat daily for 5 days
            var rrule = new Ical.Net.DataTypes.RecurrencePattern(FrequencyType.Daily, 1)
            {
                Count = 5
            };

            calendarEvent.RecurrenceRules = new List <Ical.Net.DataTypes.RecurrencePattern> {
                rrule
            };

            //Attendees
            calendarEvent.Attendees = calEvent.Attendees.Select(a => new Ical.Net.DataTypes.Attendee()
            {
                CommonName          = a.EmailAddress.Name,
                ParticipationStatus = "REQ-PARTICIPANT",
                Rsvp  = true,
                Value = new Uri($"mailto:{a.EmailAddress.Address}")
            }).ToList();

            //Alarm
            Alarm alarm = new Alarm()
            {
                Action  = AlarmAction.Display,
                Trigger = new Trigger(TimeSpan.FromDays(-1)),
                Summary = calEvent.Subject
            };

            calendarEvent.Alarms.Add(alarm);

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

            StreamWriter sw = new StreamWriter("D:\\POC\\ConsoleSOFOInvitation\\ConsoleSOFOInvitation\\invitation.ics");

            sw.Write(serializedCalendar);

            sw.Close();
        }
        public async static Task <string> Execute(string apiKey, string subject, string EmailBody, string EmailFrom, string emailto, bool?isBooked = false, SessionBookingData?data = null)
        {
            try
            {
                apiKey = "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";
                var client = new SendGridClient(apiKey);
                //var from = new EmailAddress("*****@*****.**", "Example User");
                //var Subject = "Sending with SendGrid is Fun";
                var to = new System.Net.Mail.MailAddress(emailto);
                //var plainTextContent = "and easy to do anywhere, even with C#";
                //var htmlContent = "<strong>and easy to do anywhere, even with C#</strong>";
                //var msg = MailHelper.CreateSingleEmail(from, to, Subject, plainTextContent, htmlContent);
                //var response = client.SendEmailAsync(msg);
                SendGrid.Helpers.Mail.Attachment attachment = new SendGrid.Helpers.Mail.Attachment();
                var file = "";
                if (isBooked == true && data != null)
                {
                    var calendar = new Ical.Net.Calendar();
                    var vEvent   = new CalendarEvent
                    {
                        Class       = "PUBLIC",
                        Summary     = data.SessionTitle,
                        Created     = new CalDateTime(DateTime.Now),
                        Description = data.SessionShotDescription,
                        Start       = new CalDateTime(data.SessionDate.Value),
                        //End = new CalDateTime(Convert.ToDateTime(res.EndDate)),
                        Sequence = 0,
                        Uid      = data.SessionGuid.ToString(),
                        // Location = res.Location,
                    };

                    calendar.Events.Add(vEvent);
                    var          serializer         = new CalendarSerializer(new SerializationContext());
                    var          serializedCalendar = serializer.SerializeToString(calendar);
                    var          bytesCalendar      = Encoding.UTF8.GetBytes(serializedCalendar);
                    MemoryStream ms = new MemoryStream(bytesCalendar);
                    //attachment = new System.Net.Mail.Attachment(ms, "event.ics", "text/calendar");
                    file = Convert.ToBase64String(bytesCalendar);
                }

                //var apiKey = _configuration.GetSection("SENDGRID_API_KEY").Value;
                //var client = new SendGridClient(apiKey);
                var from = new System.Net.Mail.MailAddress("*****@*****.**");

                var sendEmail = MailHelper.CreateSingleEmail(new EmailAddress(from.Address), new EmailAddress(to.Address), subject, "", EmailBody);
                sendEmail.SetSpamCheck(false);

                if (isBooked == true && data != null)
                {
                    sendEmail.AddAttachment("session.ics", file, "text/calendar", "attachment");
                }

                var response = await client.SendEmailAsync(sendEmail);

                return("");
                //return response;
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Beispiel #26
0
        private object GetCalendarFeed()
        {
            var pastDays    = 7;
            var futureDays  = 28;
            var start       = DateTime.Today.AddDays(-pastDays);
            var end         = DateTime.Today.AddDays(futureDays);
            var unmonitored = false;

            //var premiersOnly = false;
            var tags = new List <int>();

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

            // var queryPremiersOnly = Request.Query.PremiersOnly;
            var queryTags = Request.Query.Tags;

            if (queryStart.HasValue)
            {
                start = DateTime.Parse(queryStart.Value);
            }

            if (queryEnd.HasValue)
            {
                end = DateTime.Parse(queryEnd.Value);
            }

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

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

            if (queryUnmonitored.HasValue)
            {
                unmonitored = bool.Parse(queryUnmonitored.Value);
            }

            //if (queryPremiersOnly.HasValue)
            //{
            //    premiersOnly = bool.Parse(queryPremiersOnly.Value);
            //}
            if (queryTags.HasValue)
            {
                var tagInput = (string)queryTags.Value.ToString();
                tags.AddRange(tagInput.Split(',').Select(_tagService.GetTag).Select(t => t.Id));
            }

            var movies   = _movieService.GetMoviesBetweenDates(start, end, unmonitored);
            var calendar = new Ical.Net.Calendar
            {
                ProductId = "-//radarr.video//Radarr//EN"
            };

            var calendarName = "Radarr Movies Calendar";

            calendar.AddProperty(new CalendarProperty("NAME", calendarName));
            calendar.AddProperty(new CalendarProperty("X-WR-CALNAME", calendarName));

            foreach (var movie in movies.OrderBy(v => v.Added))
            {
                if (tags.Any() && tags.None(movie.Tags.Contains))
                {
                    continue;
                }

                CreateEvent(calendar, movie, true);
                CreateEvent(calendar, movie, false);
            }

            var serializer = (IStringSerializer) new SerializerFactory().Build(calendar.GetType(), new SerializationContext());
            var icalendar  = serializer.SerializeToString(calendar);

            return(new TextResponse(icalendar, "text/calendar"));
        }
Beispiel #27
0
        private object GetCalendarFeed()
        {
            var pastDays    = 7;
            var futureDays  = 28;
            var start       = DateTime.Today.AddDays(-pastDays);
            var end         = DateTime.Today.AddDays(futureDays);
            var unmonitored = Request.GetBooleanQueryParameter("unmonitored");
            var tags        = new List <int>();

            var queryPastDays   = Request.Query.PastDays;
            var queryFutureDays = Request.Query.FutureDays;
            var queryTags       = Request.Query.Tags;

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

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

            if (queryTags.HasValue)
            {
                var tagInput = (string)queryTags.Value.ToString();
                tags.AddRange(tagInput.Split(',').Select(_tagService.GetTag).Select(t => t.Id));
            }

            var books    = _bookService.BooksBetweenDates(start, end, unmonitored);
            var calendar = new Ical.Net.Calendar
            {
                ProductId = "-//readarr.com//Readarr//EN"
            };

            var calendarName = "Readarr Book Schedule";

            calendar.AddProperty(new CalendarProperty("NAME", calendarName));
            calendar.AddProperty(new CalendarProperty("X-WR-CALNAME", calendarName));

            foreach (var book in books.OrderBy(v => v.ReleaseDate.Value))
            {
                var author = _authorService.GetAuthor(book.AuthorId); // Temp fix TODO: Figure out why Album.Artist is not populated during AlbumsBetweenDates Query

                if (tags.Any() && tags.None(author.Tags.Contains))
                {
                    continue;
                }

                var occurrence = calendar.Create <CalendarEvent>();
                occurrence.Uid = "Readarr_book_" + book.Id;

                //occurrence.Status = album.HasFile ? EventStatus.Confirmed : EventStatus.Tentative;
                occurrence.Description = book.Editions.Value.Single(x => x.Monitored).Overview;
                occurrence.Categories  = book.Genres;

                occurrence.Start = new CalDateTime(book.ReleaseDate.Value.ToLocalTime())
                {
                    HasTime = false
                };

                occurrence.Summary = $"{author.Name} - {book.Title}";
            }

            var serializer = (IStringSerializer) new SerializerFactory().Build(calendar.GetType(), new SerializationContext());
            var icalendar  = serializer.SerializeToString(calendar);

            return(new TextResponse(icalendar, "text/calendar"));
        }
        public IcsClient(string url)
        {
            using (MemoryStream stream = new MemoryStream(Resource1.HugoCalender))
            {
                calendar = Ical.Net.Calendar.Load(stream);
            }

            foreach (var calEvent in calendar.Events)
            {
                if ((calEvent.Start.Year == DateTime.Now.Year && calEvent.RecurrenceRules.Count > 0) || calEvent.Start.Year == DateTime.Now.Year)
                {
                    IList <Ical.Net.DataTypes.Attendee> attendees = calEvent.Attendees;
                    DateTime dateStart = new DateTime(calEvent.Start.Ticks);
                    DateTime dateEnd;

                    if (calEvent.End != null)
                    {
                        dateEnd = new DateTime(calEvent.End.Ticks);
                    }
                    else
                    {
                        dateEnd = new DateTime(calEvent.Start.Ticks);
                    }

                    ScheduleAppointment appointment;

                    foreach (var a in attendees)
                    {
                        Attendee attender = new Attendee();
                        attender.Name  = a.Value.UserInfo;
                        attender.Email = a.CommonName;
                        attending.Add(attender);
                    }


                    if (calEvent.RecurrenceRules != null && calEvent.RecurrenceRules.Count != 0)
                    {
                        var    RecRule       = new List <RecurrencePattern>(calEvent.RecurrenceRules.AsEnumerable());
                        var    pattern       = RecRule.FirstOrDefault();
                        string stringPattern = pattern?.ToString();
                        var    ex            = pattern?.Frequency;
                        RecurrenceProperties recurrenceProperties = new RecurrenceProperties();
                        recurrenceProperties.RecurrenceType = (RecurrenceType)calEvent.RecurrenceRules[0].Frequency;

                        int[] dayInts = new int[pattern.ByDay.Count];

                        for (int i = 0; i < pattern.ByDay.Count; i++)
                        {
                            recurrenceProperties.WeekDays = (WeekDays)pattern.ByDay[i].DayOfWeek;
                        }

                        appointment = new ScheduleAppointment()
                        {
                            StartTime = dateStart, EndTime = dateEnd, Subject = calEvent.Summary, IsRecursive = true, RecurrenceRule = stringPattern, Location = calEvent.Location
                        };
                        AppointmentModels.Add(new AppointmentModel(new ScheduleAppointment()
                        {
                            StartTime = dateStart, EndTime = dateEnd, Subject = calEvent.Summary, IsRecursive = true, RecurrenceRule = stringPattern, Location = calEvent.Location
                        }, attending, stringPattern));
                    }
                    else
                    {
                        appointment = new ScheduleAppointment()
                        {
                            StartTime = dateStart, EndTime = dateEnd, Subject = calEvent.Summary, IsRecursive = true, Location = calEvent.Location
                        };
                        AppointmentModels.Add(new AppointmentModel(new ScheduleAppointment()
                        {
                            StartTime = dateStart, EndTime = dateEnd, Subject = calEvent.Summary, IsRecursive = true, Location = calEvent.Location
                        }, attending, null));
                    }

                    ScheduleAppointments.Add(appointment);
                }
            }
        }
Beispiel #29
0
        public OperationResultDto SendRegistrationEmail(EventRegistrationDTO registrationInfo)
        {
            var mapping = CompanyEventQuizMappingModel.GetOneById(registrationInfo.eventQuizMappingId).Value;

            if (mapping == null)
            {
                return(OperationResultDto.Error("There is no event for this info."));
            }

            var acDomain = CompanyAcServerModel.GetOneById(mapping.CompanyAcDomain.Id).Value;
            var apiUrl   = new Uri(acDomain.AcServer);
            var proxy    = new AdobeConnectProxy(new AdobeConnectProvider(new ConnectionDetails(apiUrl)), Logger, apiUrl);

            var loginResult = proxy.Login(new UserCredentials(acDomain.Username, acDomain.Password));

            if (!loginResult.Success)
            {
                throw new InvalidOperationException($"Can't login to AC url {acDomain.AcServer} user {acDomain.Username}");
            }

            var eventInfo = proxy.GetScoInfo(mapping.AcEventScoId);

            if (!eventInfo.Success)
            {
                throw new InvalidOperationException(eventInfo.Status.GetErrorInfo());
            }

            List <string> emailsNotSend = new List <string>();

            try
            {
                //todo: create model based on success/fail
                var model = new EventQuizRegistrationModel(Settings)
                {
                    FirstName      = registrationInfo.FirstName,
                    LastName       = registrationInfo.LastName,
                    EventName      = eventInfo.ScoInfo.Name,
                    EventDesc      = eventInfo.ScoInfo.Description,
                    EventScoId     = eventInfo.ScoInfo.ScoId,
                    EventStartDate = DateTimeHelper.ConvertToEST(eventInfo.ScoInfo.BeginDate).Value,
                    EventEndDate   = DateTimeHelper.ConvertToEST(eventInfo.ScoInfo.EndDate).Value,
                    MailSubject    = Emails.RegistrationSubject,
                    MeetingUrl     = acDomain.AcServer.TrimEnd('/') + "/" + eventInfo.ScoInfo.SourceSco.UrlPath.TrimStart('/'),
                    Email          = registrationInfo.Email
                };

                var attachments = new List <System.Net.Mail.Attachment>();

                var e = new Event
                {
                    //DtStart = new CalDateTime(DateTimeHelper.ConvertToEST(model.EventStartDate).Value),
                    //DtEnd = new CalDateTime(DateTimeHelper.ConvertToEST(model.EventEndDate).Value),
                    DtStart     = new CalDateTime(eventInfo.ScoInfo.BeginDate),
                    DtEnd       = new CalDateTime(eventInfo.ScoInfo.EndDate),
                    Summary     = $"{model.EventName}",
                    Description = model.MeetingUrl,
                    Url         = new Uri(model.MeetingUrl)
                };

                var calendar = new Calendar();
                calendar.Events.Add(e);

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

                //var ms = new MemoryStream();
                //using (var writer = new StreamWriter(ms))
                //{
                //    writer.Write(serializedCalendar);
                //    writer.Flush();
                //}
                //ms.Position = 0;
                byte[] bytes = new byte[serializedCalendar.Length * sizeof(char)];
                Buffer.BlockCopy(serializedCalendar.ToCharArray(), 0, bytes, 0, bytes.Length);

                var contype = new System.Net.Mime.ContentType("text/calendar");
                contype.Parameters.Add("method", "REQUEST");
                contype.Parameters.Add("name", "EventInformation.ics");
                var calendarItem = new System.Net.Mail.Attachment(new MemoryStream(bytes), contype);
                calendarItem.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
                attachments.Add(calendarItem);

                var sentSuccessfully = MailModel.SendEmailSync($"{model.FirstName} {model.LastName}", model.Email,
                                                               Emails.RegistrationSubject,
                                                               model, Common.AppEmailName, Common.AppEmail, attachments: attachments);
                if (!sentSuccessfully)
                {
                    emailsNotSend.Add(model.Email);
                }
            }
            catch (Exception e)
            {
                Logger.Error($"[SendRegistrationEmail] error.", e);
                emailsNotSend.Add(registrationInfo.Email);
            }


            return(emailsNotSend.Any() ? OperationResultDto.Error("Not all emails were sent correctly") : OperationResultDto.Success());
        }
        public async Task <IActionResult> Create(CalendarSogo.Models.Event ev)
        {
            try
            {
                CalendarEvent e = new CalendarEvent()
                {
                    Description = ev.Description,
                    Summary     = ev.Summary,
                    Start       = new CalDateTime(ev.Start),
                    End         = new CalDateTime(ev.End),
                    Location    = "301 cabinet",
                    Comments    = new List <string>()
                    {
                        "comment1"
                    },
                    Contacts = new List <string>()
                    {
                        "Contacts"
                    },
                    GeographicLocation = new GeographicLocation(),

                    Organizer = new Organizer()
                    {
                        CommonName = "Organizer name",
                        Value      = new Uri("mailto:[email protected]")
                    },
                    Attendees = new List <Attendee>()
                    {
                        new Attendee(new Uri("mailto:[email protected]"))
                        {
                            CommonName = "test1 name",
                            Role       = ParticipationRole.RequiredParticipant
                        },
                        new Attendee(new Uri("mailto:[email protected]"))
                        {
                            CommonName = "test2 name",
                            Role       = ParticipationRole.RequiredParticipant
                        },
                    }
                };


                string readAll;
                //HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://mx.sailau09.kz/SOGo/dav/[email protected]/Calendar/personal/" + e.Uid + ".ics");
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://mx.sailau09.kz/SOGo/dav/[email protected]/Calendar/dddd" + e.Uid + ".ics");
                request.Credentials = new NetworkCredential("*****@*****.**", "!QAZ3edc");
                request.ContentType = "text/calendar";
                request.Headers.Add("If-None-Match", "*");
                request.Method = "PUT";
                request.ServerCertificateValidationCallback = delegate { return(true); };// при публикации на боевой сервер убрать

                Ical.Net.Calendar calendar = new Ical.Net.Calendar();
                calendar.Events.Add(e);
                CalendarSerializer calendarSerializer = new CalendarSerializer();
                // возьмем поток и запишем туда наше мероприятие
                using (var stream = request.GetRequestStream())
                {
                    calendarSerializer.Serialize(calendar, stream, Encoding.UTF8);
                }
                HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync();

                using (Stream stream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        var statusCode = response.StatusCode;
                        readAll = reader.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
                return(BadRequest(new { message = ex.Message }));
            }
            return(RedirectToAction("Index"));
        }