Ejemplo n.º 1
0
        public int addFrostyRegistration(WebFrostyRegistration webRegistration)
        {
            // Check if registration is enabled for this event occurrence.
            EventOccurrence eventOccurrence = db.EventOccurrences
                                              .SingleOrDefault(e => e.id == webRegistration.eventOccurrenceId);

            if (eventOccurrence != null)
            {
                if (!eventOccurrence.isActive)
                {
                    throw new Exception("You cannot register for this event because it is not active");
                }
                FrostyRegistration registration = new FrostyRegistration();
                registration.eventOccurrenceId = webRegistration.eventOccurrenceId;
                registration.userId            = this.me.id;
                registration.isPaid            = false;
                registration.isMinor           = webRegistration.isMinor;
                registration.dateCreated       = DateTime.UtcNow;

                db.FrostyRegistrations.Add(registration);
                db.SaveChanges();

                return(registration.id);
            }
            else
            {
                throw new PermissionDeniedException();
            }
        }
Ejemplo n.º 2
0
 private Boolean IsBlackedOut(EventOccurrence occurrrence, List <EventBlackout> blackoutDates)
 {
     foreach (EventBlackout blackoutDate in blackoutDates)
     {
         if (datesOverlap(occurrrence, blackoutDate.Start, blackoutDate.End))
         {
             return(true);
         }
     }
     return(false);
 }
        private static void CreateEventOccurrence(string url)
        {
            //Create a new client using default network credentials
            IRecordsManagerClient client = RecordsManagerClientFactory.Create(url);

            //Currently for a production scenario, you would need to get the retention trigger by ID
            //This sample finds the first manual, event-based, retention trigger and uses that instead.
            RetentionTrigger retentionTrigger = RetentionTriggerIntegrations.GetFirstManualEventTrigger(client);

            //Create an event occurrence for the specified trigger using the specified property name & value
            EventOccurrence eventOccurrence = EventOccurrenceIntegration.CreatePropertyEventOccurrence(client, retentionTrigger.Id, "LoanNumber", "12345");
        }
Ejemplo n.º 4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EventOccurrenceViewModel"/> class.
 /// </summary>
 /// <param name="item">The item.</param>
 public EventOccurrenceViewModel(EventOccurrence item, CultureInfo uiCulture)
 {
     this.Id           = item.Event.Id;
     this.Title        = item.Event.Title[uiCulture.Name];
     this.Description  = item.Event.Description[uiCulture.Name];
     this.Start        = item.Event.AllDayEvent ? item.StartDate.Add(new TimeSpan(item.StartDate.Ticks - item.StartDate.ToSitefinityUITime().Ticks)) : item.StartDate;
     this.End          = item.EndDate.HasValue ? item.Event.AllDayEvent ? item.EndDate.Value.Add(new TimeSpan(item.EndDate.Value.Ticks - item.EndDate.Value.ToSitefinityUITime().Ticks)).AddDays(-1) : item.EndDate.Value : DateTime.MaxValue;
     this.RecurrenceID = item.IsRecurrent ? item.Event.Id : (Guid?)null;
     this.IsAllDay     = item.Event.AllDayEvent;
     this.CalendarId   = item.Event.ParentId;
     this.EventUrl     = item.Event.ItemDefaultUrl[uiCulture.Name];
 }
Ejemplo n.º 5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SchedulerEventViewModel"/> class.
 /// </summary>
 /// <param name="item">The item.</param>
 public SchedulerEventViewModel(EventOccurrence item)
 {
     this.Id           = item.Event.Id;
     this.Title        = item.Title;
     this.Description  = item.Description;
     this.Start        = item.StartDate;
     this.End          = item.EndDate != null ? (item.Event.AllDayEvent ? item.EndDate.Value.AddDays(-1) : item.EndDate.Value) : DateTime.MaxValue;
     this.RecurrenceID = item.IsRecurrent ? item.Event.Id : (Guid?)null;
     this.IsAllDay     = item.Event.AllDayEvent;
     this.CalendarId   = item.Event.ParentId;
     this.Color        = item.Event.Parent.Color;
 }
        public WebEventOccurrence getEventOccurrence(int id)
        {
            EventOccurrence eventOccurrence = db.EventOccurrences.SingleOrDefault(u => u.id == id);

            if (eventOccurrence != null)
            {
                return(eventOccurrence.convert());
            }
            else
            {
                throw new PermissionDeniedException();
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Add Recurring event.
        /// </summary>
        /// <param name="celebrationEvent">CelebrationEvent instance.</param>
        /// <param name="upcomingEventDate">upcoming event date.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        private async Task AddRecurringEventAsync(CelebrationEvent celebrationEvent, DateTime upcomingEventDate)
        {
            var            timespan = Array.ConvertAll <string, int>(ApplicationSettings.TimeToPostCelebration.Split(':'), Convert.ToInt32);
            DateTime       upcomingEventDateTime      = upcomingEventDate.AddHours(timespan[0]).AddMinutes(timespan[1]).AddSeconds(timespan[2]);
            DateTimeOffset upcomingEventDateTimeInUTC = TimeZoneInfo.ConvertTimeToUtc(upcomingEventDateTime, TimeZoneInfo.FindSystemTimeZoneById(celebrationEvent.TimeZoneId));

            EventOccurrence eventOccurrence = new EventOccurrence
            {
                EventId = celebrationEvent.Id,
                Date    = upcomingEventDateTimeInUTC,
            };

            await this.eventHelper.AddRecurringEventAsync(eventOccurrence);
        }
Ejemplo n.º 8
0
        public void updateBFKSRegistration(WebBFKSRegistration webRegistration)
        {
            // Check if registration is enabled for this event occurrence.
            EventOccurrence eventOccurrence = db.EventOccurrences
                                              .SingleOrDefault(e => e.id == webRegistration.eventOccurrenceId);

            if (eventOccurrence != null)
            {
                if (!eventOccurrence.isActive)
                {
                    throw new Exception("You cannot register for this event because it is not active");
                }
                BFKSRegistration registration = db.BFKSRegistrations
                                                .SingleOrDefault(r => r.id == webRegistration.id);
                if (registration != null && (registration.userId == me.id || me.type == "admin"))
                {
                    registration.eventOccurrenceId = webRegistration.eventOccurrenceId;
                    // Only allow admins to manually mark registration as being paid (e.g. in person with cash/check).
                    if (me.type == "admin")
                    {
                        registration.isPaid = webRegistration.isPaid;
                    }
                    registration.teamName      = webRegistration.teamName;
                    registration.teamCaptainId = webRegistration.teamCaptainId;

                    db.BFKSBowlers.RemoveRange(registration.bowlers);

                    registration.bowlers = new List <BFKSBowler>();
                    foreach (WebBFKSBowler webBowler in webRegistration.bowlers)
                    {
                        BFKSBowler bowler = new BFKSBowler();
                        bowler.userId     = webBowler.userId;
                        bowler.name       = webBowler.name;
                        bowler.tshirtSize = webBowler.tshirtSize;
                        registration.bowlers.Add(bowler);
                    }

                    db.SaveChanges();
                }
                else
                {
                    throw new PermissionDeniedException();
                }
            }
            else
            {
                throw new PermissionDeniedException();
            }
        }
        /// <inheritdoc/>
        public async Task UpdateEventOccurrenceAsync(EventOccurrence eventOccurrence)
        {
            if (eventOccurrence.Id == null)
            {
                throw new ArgumentException("Occurrence must have an ID", nameof(eventOccurrence));
            }

            await this.EnsureInitializedAsync();

            eventOccurrence.TimeToLive = this.GetTimeToLive(eventOccurrence.DateTime);

            var documentUri = UriFactory.CreateDocumentUri(this.database.Id, this.occurencesCollection.Id, eventOccurrence.Id);

            await this.documentClient.ReplaceDocumentAsync(documentUri, eventOccurrence);
        }
        /// <inheritdoc/>
        public async Task <EventOccurrence> AddEventOccurrenceAsync(EventOccurrence eventOccurrence)
        {
            if (eventOccurrence.Id != null)
            {
                throw new ArgumentException("A new occurrence must not have an assigned ID", nameof(eventOccurrence));
            }

            await this.EnsureInitializedAsync();

            eventOccurrence.TimeToLive = this.GetTimeToLive(eventOccurrence.GetLastAllowableTimeToSendNotification());

            var response = await this.documentClient.CreateDocumentAsync(this.occurencesCollection.SelfLink, eventOccurrence);

            return((EventOccurrence)(dynamic)response.Resource);
        }
Ejemplo n.º 11
0
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter the URL for your Information Lifecycle server...");

            string url = Console.ReadLine();

            //Create a new client using default network credentials
            IRecordsManagerClient client = new RecordsManagerClient(url);

            //Currently for a production scenario, you would need to get the retention trigger by ID
            //This sample finds the first manual, event-based, retention trigger and uses that instead.
            RetentionTrigger retentionTrigger = RetentionTriggerIntegrations.GetFirstManualEventTrigger(client);

            //Create an event occurrence for the specified trigger using the specified property name & value
            EventOccurrence eventOccurrence = EventOccurrenceIntegration.CreatePropertyEventOccurrence(client, retentionTrigger.Id, "LoanNumber", "12345");
        }
Ejemplo n.º 12
0
        /// <summary>
        /// update recurring event.
        /// </summary>
        /// <param name="eventId">eventId.</param>
        /// <param name="eventStatus">event status.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        public async Task UpdateRecurringEventAsync(string eventId, EventStatus eventStatus)
        {
            await this.EnsureInitializedAsync();

            var options = new FeedOptions {
                EnableCrossPartitionQuery = true
            };
            var document = this.documentClient.CreateDocumentQuery <EventOccurrence>(this.occurencesCollection.SelfLink, options)
                           .Where(x => x.EventId == eventId).AsEnumerable().FirstOrDefault();

            if (document != null)
            {
                EventOccurrence eventOccurrence = (dynamic)document;
                eventOccurrence.Status = eventStatus;
                await this.documentClient.ReplaceDocumentAsync(document.SelfLink, eventOccurrence);
            }
        }
        public void updateEventOccurrence(int id, WebEventOccurrence webEventOccurrence)
        {
            EventOccurrence eventOccurrence = db.EventOccurrences.SingleOrDefault(u => u.id == id);

            if (eventOccurrence != null && me.type == "admin")
            {
                eventOccurrence.isActive    = webEventOccurrence.isActive;
                eventOccurrence.type        = webEventOccurrence.type;
                eventOccurrence.description = webEventOccurrence.description;
                eventOccurrence.date        = webEventOccurrence.date;
                db.SaveChanges();
            }
            else
            {
                throw new PermissionDeniedException();
            }
        }
Ejemplo n.º 14
0
        public static EventOccurrence CreatePropertyEventOccurrence(IRecordsManagerClient client, long triggerId, string propertyName, string propertyValue)
        {
            var eventOccurrence = new EventOccurrence();

            eventOccurrence.EventDate      = DateTime.Now; //EventDate is when this occurrence actually happened; does not have to be DateTime.Now
            eventOccurrence.EventTriggerId = triggerId;
            eventOccurrence.TargetType     = EventOccurrenceTargetType.Property;
            eventOccurrence.TargetProperty = propertyName;
            eventOccurrence.TargetValue    = propertyValue;

            Debug.Assert(eventOccurrence.Id == 0, "The new event occurrence should have an ID equal to zero.");

            eventOccurrence = client.CreateEventOccurrence(eventOccurrence);

            Debug.Assert(eventOccurrence.Id > 0, "The created event occurrence should have an ID greater than zero.");

            return(eventOccurrence);
        }
        private static void CreateEventOccurrence(string url, string user, string pwd)
        {
            RestApiIntegrations.Credentials = new System.Net.NetworkCredential(user, pwd);

            RestApiIntegrations.InfoLifecycleServerUrl = new Uri(url, UriKind.Absolute);

            RetentionTrigger trigger = RestApiIntegrations.GetFirstManualEventTrigger();

            EventOccurrence eventOccurrence = new EventOccurrence();

            eventOccurrence.EventDate      = DateTime.SpecifyKind(DateTime.Parse("1/15/2015"), DateTimeKind.Local);
            eventOccurrence.TargetType     = EventOccurrenceTargetType.Property;
            eventOccurrence.TargetProperty = "EmployeeId";
            eventOccurrence.TargetValue    = "12345";
            eventOccurrence.EventTriggerId = trigger.Id;

            eventOccurrence = RestApiIntegrations.CreateEventOccurrence(eventOccurrence);
        }
        public int addEventOccurrence(WebEventOccurrence webEventOccurrence)
        {
            if (me.type == "admin")
            {
                EventOccurrence eventOccurrence = new EventOccurrence();
                eventOccurrence.isActive    = webEventOccurrence.isActive;
                eventOccurrence.type        = webEventOccurrence.type;
                eventOccurrence.description = webEventOccurrence.description;
                eventOccurrence.date        = webEventOccurrence.date;
                db.EventOccurrences.Add(eventOccurrence);
                db.SaveChanges();

                return(eventOccurrence.id);
            }
            else
            {
                throw new PermissionDeniedException();
            }
        }
        public int addEventOccurrence(WebEventOccurrence webEventOccurrence)
        {
            if (me.type == "admin")
            {
                EventOccurrence eventOccurrence = new EventOccurrence();
                eventOccurrence.isActive = webEventOccurrence.isActive;
                eventOccurrence.type = webEventOccurrence.type;
                eventOccurrence.description = webEventOccurrence.description;
                eventOccurrence.date = webEventOccurrence.date;
                db.EventOccurrences.Add(eventOccurrence);
                db.SaveChanges();

                return eventOccurrence.id;
            }
            else
            {
                throw new PermissionDeniedException();
            }
        }
        public static EventOccurrence CreateEventOccurrence(EventOccurrence eventOccurrence)
        {
            string jsonResponse = null;

            //Make HTTP POST request and populate json variable...
            using (var client = GetWebClient())
            {
                string endpoint = RestApiV1Constants.POST_EVENTOCCURRENCE;

                string jsonRequest = JsonConvert.SerializeObject(eventOccurrence, outboundJsonSettings);

                jsonResponse = client.UploadString(new Uri(endpoint, UriKind.Relative), "POST", jsonRequest);
            }

            var result = JsonConvert.DeserializeObject <EventOccurrence>(jsonResponse, inboundJsonSettings);

            //Remove Debug.Assert in a production environment...
            Debug.Assert(result.Id != 0, "Invalid Event Occurrence! The Id should have been populated after creation.");

            return(result);
        }
Ejemplo n.º 19
0
        public int addBFKSRegistration(WebBFKSRegistration webRegistration)
        {
            // Check if registration is enabled for this event occurrence.
            EventOccurrence eventOccurrence = db.EventOccurrences
                                              .SingleOrDefault(e => e.id == webRegistration.eventOccurrenceId);

            if (eventOccurrence != null)
            {
                if (!eventOccurrence.isActive)
                {
                    throw new Exception("You cannot register for this event because it is not active");
                }
                BFKSRegistration registration = new BFKSRegistration();
                registration.eventOccurrenceId = webRegistration.eventOccurrenceId;
                registration.userId            = this.me.id;
                registration.isPaid            = false;
                registration.teamName          = webRegistration.teamName;
                registration.teamCaptainId     = webRegistration.teamCaptainId;
                registration.dateCreated       = DateTime.UtcNow;

                registration.bowlers = new List <BFKSBowler>();
                foreach (WebBFKSBowler webBowler in webRegistration.bowlers)
                {
                    BFKSBowler bowler = new BFKSBowler();
                    bowler.userId     = webBowler.userId;
                    bowler.name       = webBowler.name;
                    bowler.tshirtSize = webBowler.tshirtSize;
                    registration.bowlers.Add(bowler);
                }

                db.BFKSRegistrations.Add(registration);
                db.SaveChanges();

                return(registration.id);
            }
            else
            {
                throw new PermissionDeniedException();
            }
        }
Ejemplo n.º 20
0
        public void updateFrostyRegistration(WebFrostyRegistration webRegistration)
        {
            // Check if registration is enabled for this event occurrence.
            EventOccurrence eventOccurrence = db.EventOccurrences
                                              .SingleOrDefault(e => e.id == webRegistration.eventOccurrenceId);

            if (eventOccurrence != null)
            {
                if (!eventOccurrence.isActive)
                {
                    throw new Exception("You cannot register for this event because it is not active");
                }
                FrostyRegistration registration = db.FrostyRegistrations
                                                  .SingleOrDefault(r => r.id == webRegistration.id);
                if (registration != null && (registration.userId == me.id || me.type == "admin"))
                {
                    registration.eventOccurrenceId = webRegistration.eventOccurrenceId;
                    // Only allow admins to manually mark registration as being paid (e.g. in person with cash/check).
                    if (me.type == "admin")
                    {
                        registration.isPaid = webRegistration.isPaid;
                    }
                    registration.isMinor = webRegistration.isMinor;

                    db.SaveChanges();
                }
                else
                {
                    throw new PermissionDeniedException();
                }
            }
            else
            {
                throw new PermissionDeniedException();
            }
        }
        // Send a messsage to the owner of the given event, reminding them that their event is coming up
        private async Task SendEventReminderAsync(CelebrationEvent celebrationEvent, DateTimeOffset currentDateTimeOffset)
        {
            this.logProvider.LogInfo($"Sending reminder for event {celebrationEvent.Id} (owner={celebrationEvent.OwnerAadObjectId}, date={celebrationEvent.Date.ToShortDateString()})");

            // Determine the next occurrence of the event
            var deliveryTimeZone = TimeZoneInfo.FindSystemTimeZoneById(celebrationEvent.TimeZoneId);
            var currentTimeInDeliveryTimeZone = TimeZoneInfo.ConvertTimeFromUtc(currentDateTimeOffset.UtcDateTime, deliveryTimeZone);
            var upcomingEventDateTime         = Common.GetNextOccurrenceAfterDateTime(celebrationEvent.Date.Add(this.timeToPostPreview), currentTimeInDeliveryTimeZone);
            var upcomingEventDateTimeInUTC    = TimeZoneInfo.ConvertTimeToUtc(upcomingEventDateTime, deliveryTimeZone);

            // Do not send reminder if the next occurrence is not in the window
            var timeUntilNextOccurrence = upcomingEventDateTimeInUTC - currentDateTimeOffset;

            if ((timeUntilNextOccurrence.TotalMinutes < 0) ||
                (upcomingEventDateTimeInUTC - currentDateTimeOffset) > TimeSpan.FromDays(this.daysInAdvanceToSendEventPreview))
            {
                this.logProvider.LogInfo($"Next occurrence of event {celebrationEvent.Id} is not in the next {this.daysInAdvanceToSendEventPreview} days");
                return;
            }

            // Add an entry to Occurrence collection for the event, so we know that we processed it
            var eventOccurrence = new EventOccurrence
            {
                EventId          = celebrationEvent.Id,
                OwnerAadObjectId = celebrationEvent.OwnerAadObjectId,
                DateTime         = upcomingEventDateTimeInUTC,
            };

            eventOccurrence = await this.eventDataProvider.AddEventOccurrenceAsync(eventOccurrence);

            // Do not send reminder if we are within the period specified in the configuration
            if ((upcomingEventDateTimeInUTC - currentDateTimeOffset) < this.minimumTimeToProcessEvent)
            {
                this.logProvider.LogInfo($"Not sending reminder for event {celebrationEvent.Id} which is due in less than {(int)this.minimumTimeToProcessEvent.TotalHours} hours");
                return;
            }

            // Get event owner information
            var user = await this.userManagementHelper.GetUserByAadObjectIdAsync(celebrationEvent.OwnerAadObjectId);

            await this.EnsureConversationWithUserAsync(user);

            // Send reminder of event to the owner
            var previewCard = CelebrationCard.GetPreviewCard(celebrationEvent, eventOccurrence.Id, user.DisplayName);
            var message     = string.Format(Strings.EventPreviewMessageText, user.DisplayName);
            var activity    = new Activity(ActivityTypes.Message)
            {
                Conversation = new ConversationAccount {
                    Id = user.ConversationId
                },
                Recipient = new ChannelAccount {
                    Id = user.TeamsId
                },
                Text        = message,
                Summary     = message,
                Attachments = new List <Attachment> {
                    previewCard.ToAttachment()
                },
                ServiceUrl = user.ServiceUrl,
            };

            // Add new entry to EventMessages collection for message type "preview" to track the status of message sent
            var eventMessage = new EventMessage
            {
                EventId      = celebrationEvent.Id,
                OccurrenceId = eventOccurrence.Id,
                Activity     = activity,
                TenantId     = user.TenantId,
                MessageType  = MessageType.Preview,
                ExpireAt     = upcomingEventDateTimeInUTC.AddHours(24),
            };

            eventMessage = await this.eventDataProvider.AddEventMessageAsync(eventMessage);

            // Send the message
            try
            {
                await eventMessage.SendAsync(this.connectorClientFactory);

                this.logProvider.LogInfo($"Reminder message sent to the owner of event {celebrationEvent.Id}");
            }
            catch (Exception ex)
            {
                this.logProvider.LogError($"Failed to send reminder for event {celebrationEvent.Id}", ex, new Dictionary <string, string>
                {
                    { "EventId", eventMessage.EventId },
                    { "OccurrenceId", eventMessage.OccurrenceId },
                    { "ConversationId", user.ConversationId },
                    { "OccurrenceDateTime", eventOccurrence.DateTime.ToString() },
                    { "LastAttemptTime", DateTimeOffset.UtcNow.ToString() },
                    { "LastAttemptStatusCode", eventMessage.MessageSendResult?.StatusCode.ToString() },
                    { "ResponseBody", eventMessage.MessageSendResult?.ResponseBody },
                });
                throw;
            }
            finally
            {
                // Record the result of the send
                await this.eventDataProvider.UpdateEventMessageAsync(eventMessage);
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Add recurring event.
        /// </summary>
        /// <param name="recurringEvent">EventOccurrence instance.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        public async Task AddRecurringEventAsync(EventOccurrence recurringEvent)
        {
            await this.EnsureInitializedAsync();

            await this.documentClient.CreateDocumentAsync(this.occurencesCollection.SelfLink, recurringEvent);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Process request to send preview card
        /// </summary>
        /// <param name="currentDateTime">Current dateTime</param>
        /// <returns>A <see cref="Task"/>Representing the asynchronous operation</returns>
        public async Task <HttpResponseMessage> Post(string currentDateTime = "")
        {
            this.logProvider.LogInfo($"Processing events to send the reminder to owner. CurrentDateTime:{currentDateTime}");

            DateTimeOffset currentDateTimeOffset;

            if (!DateTimeOffset.TryParse(currentDateTime, null, DateTimeStyles.AdjustToUniversal, out currentDateTimeOffset))
            {
                currentDateTimeOffset = DateTimeOffset.UtcNow;
            }

            var events = await(await this.eventHelper.GetCelebrationEventsAsync(GetEventQuery(currentDateTimeOffset.Date))).ToListAsync();

            this.logProvider.LogInfo($"found {events.Count} which are coming in next 72 hours.");
            if (events.Count > 0)
            {
                var existingRecurringEvents = await(await this.eventHelper.GetRecurringEventsAsync(events.Select(x => x.Id).ToList())).ToListAsync();

                this.logProvider.LogInfo($"Found {existingRecurringEvents.Count} for which reminder has already sent");
                int    lastAttemptStatusCode = (int)HttpStatusCode.OK;
                string responseBody          = string.Empty;

                // remove events which exist in Occurrences collection
                events.RemoveAll(x => existingRecurringEvents.Any(y => y.EventId == x.Id));

                if (events.Count > 0)
                {
                    this.users = await this.userManagementHelper.GetUsersByAadObjectIdsAsync(events.Select(x => x.OwnerAadObjectId).ToList());

                    this.connectorServiceHelper = new ConnectorServiceHelper(this.CreateConnectorClient(this.users.FirstOrDefault().ServiceUrl), this.logProvider);
                }

                // Loop each event and make entry in Occurrences collection to send preview and event card.
                foreach (var celebrationEvent in events)
                {
                    this.logProvider.LogInfo("Processing event to send reminder", new Dictionary <string, string>()
                    {
                        { "EventId", celebrationEvent.Id }, { "UserObjectId", celebrationEvent.OwnerAadObjectId }
                    });

                    // Get event owner information.
                    var user = this.users.Where(x => x.AadObjectId == celebrationEvent.OwnerAadObjectId).FirstOrDefault();

                    // update conversation id if it is null.
                    await this.ModifyUserDetailsAsync(user);

                    DateTime       upcomingEventDate          = Common.GetUpcomingEventDate(celebrationEvent.Date, currentDateTimeOffset.Date);
                    var            timespan                   = Array.ConvertAll <string, int>(ApplicationSettings.TimeToPostCelebration.Split(':'), Convert.ToInt32);
                    DateTime       upcomingEventDateTime      = upcomingEventDate.AddHours(timespan[0]).AddMinutes(timespan[1]);
                    DateTimeOffset upcomingEventDateTimeInUTC = TimeZoneInfo.ConvertTimeToUtc(upcomingEventDateTime, TimeZoneInfo.FindSystemTimeZoneById(celebrationEvent.TimeZoneId));

                    // add an entry to Occurrence collection for all the upcoming event.
                    EventOccurrence eventOccurrence = new EventOccurrence
                    {
                        EventId = celebrationEvent.Id,
                        Date    = upcomingEventDateTimeInUTC,
                    };

                    await this.eventHelper.AddRecurringEventAsync(eventOccurrence);

                    // Do not send reminder if event is today.
                    if (upcomingEventDate != currentDateTimeOffset.Date)
                    {
                        // Add new entry to EventMessages collection for reminder.
                        EventMessage eventMessage = new EventMessage
                        {
                            OccurrenceId = eventOccurrence.Id,
                            EventId      = celebrationEvent.Id,
                            Activity     = this.GetEventMessageActivity(celebrationEvent, user),
                            MessageType  = MessageType.Preview,
                            ExpireAt     = upcomingEventDate.AddHours(24),
                        };

                        await this.eventHelper.AddEventMessageAsync(eventMessage);

                        bool      isMessageSentSuccessfully = false;
                        Exception exception = null;

                        try
                        {
                            HeroCard previewCard = CelebrationCard.GetPreviewCard(eventMessage.Activity);

                            string message = string.Format(Strings.PreviewText, user.UserName);

                            this.logProvider.LogInfo("Sending reminder message to the owner of the event", new Dictionary <string, string>()
                            {
                                { "EventId", celebrationEvent.Id },
                                { "Attachment", Newtonsoft.Json.JsonConvert.SerializeObject(previewCard) },
                                { "Message", message },
                            });

                            // Send reminder of event to owner.
                            await this.connectorServiceHelper.SendPersonalMessageAsync(
                                message,
                                new List <Attachment> {
                                previewCard.ToAttachment()
                            },
                                user.ConversationId);

                            this.logProvider.LogInfo($"Reminder message sent to the owner of the event. EventId: {celebrationEvent.Id}");
                        }
                        catch (HttpException httpException)
                        {
                            lastAttemptStatusCode = httpException.GetHttpCode();
                            responseBody          = httpException.GetHtmlErrorMessage();
                            exception             = httpException;
                        }
                        catch (ErrorResponseException errorResponseException)
                        {
                            lastAttemptStatusCode = (int)errorResponseException.Response.StatusCode;
                            responseBody          = errorResponseException.Response.Content.ToString();
                            exception             = errorResponseException;
                        }
                        catch (Exception ex)
                        {
                            lastAttemptStatusCode = (int)HttpStatusCode.BadRequest;
                            responseBody          = ex.ToString();
                        }
                        finally
                        {
                            if (!isMessageSentSuccessfully)
                            {
                                this.logProvider.LogError("Failed to send reminder for upcoming event.", exception, new Dictionary <string, string>
                                {
                                    { "EventId", eventMessage.EventId },
                                    { "OccurrenceId", eventMessage.OccurrenceId },
                                    { "eventActivity", eventMessage.Activity.ToString() },
                                    { "LastAttemptStatusCode", lastAttemptStatusCode.ToString() },
                                    { "LastAttemptTime", DateTime.UtcNow.ToString() },
                                    { "ConversationId", user.ConversationId },
                                });
                            }

                            MessageSendResult messageSendResult = new MessageSendResult()
                            {
                                LastAttemptTime = DateTime.UtcNow,
                                StatusCode      = lastAttemptStatusCode,
                                ResponseBody    = responseBody,
                            };

                            await this.eventHelper.UpdateEventMessageAsync(eventMessage.Id, messageSendResult);
                        }
                    }
                    else
                    {
                        this.logProvider.LogInfo("Not sending reminder for this event as its upcoming event date is today.");
                    }
                }
            }

            return(new HttpResponseMessage(HttpStatusCode.OK));
        }
Ejemplo n.º 24
0
 private Boolean datesOverlap(EventOccurrence occ1, DateTime startDate, DateTime endDate)
 {
     return(datesOverlap(occ1.Start, occ1.End, startDate, endDate));
 }
Ejemplo n.º 25
0
 private void OnEventOccurrence(EventOccurrence eventOccurrence)
 {
     Clients.Group(eventOccurrence.OrganizationId).eventOccurrence(eventOccurrence);
 }
Ejemplo n.º 26
0
 // Mark the given occurrence as already sent
 private Task MarkEventOccurrenceAsSentAsync(EventOccurrence occurrence)
 {
     occurrence.Status = EventStatus.Sent;
     return(this.eventDataProvider.UpdateEventOccurrenceAsync(occurrence));
 }
        /// <summary>
        /// Add an entry to EventMessages collection.
        /// </summary>
        /// <param name="conversationId">conversationId</param>
        /// <param name="recurringEvent">EventOccurrence instance</param>
        /// <param name="celebrationEvent">CelebrationEvent instance.</param>
        /// <param name="user">User instance.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        private async Task <EventMessage> AddEntryToEventMessagesCollection(string conversationId, EventOccurrence recurringEvent, CelebrationEvent celebrationEvent, User user)
        {
            EventMessage eventMessage = new EventMessage
            {
                OccurrenceId = recurringEvent.Id,
                EventId      = celebrationEvent.Id,
                Activity     = this.GetEventMessageActivity(celebrationEvent, user, conversationId),
                MessageType  = MessageType.Event,
                ExpireAt     = recurringEvent.Date.AddHours(12),
            };

            // Add new entry to EventMessages collection for reminder.
            await this.eventHelper.AddEventMessageAsync(eventMessage);

            return(eventMessage);
        }