public async Task SendBatchMessagesActivitySuccess_ForTeamRecipientTypeTest()
        {
            // Arrange
            var activity = this.GetSendBatchMessagesActivity();
            List <SentNotificationDataEntity> batch = new List <SentNotificationDataEntity>()
            {
                new SentNotificationDataEntity()
                {
                    RecipientType = SentNotificationDataEntity.TeamRecipientType,
                    RecipientId   = "recipientId",
                },
            };
            NotificationDataEntity notification = new NotificationDataEntity()
            {
                Id = "notificationId",
            };

            this.sendQueue
            .Setup(x => x.SendAsync(It.IsAny <IEnumerable <SendQueueMessageContent> >()))
            .Returns(Task.CompletedTask);

            // Act
            Func <Task> task = async() => await activity.RunAsync((notification.Id, batch));

            // Assert
            await task.Should().NotThrowAsync();

            this.sendQueue.Verify(x => x.SendAsync(It.Is <IEnumerable <SendQueueMessageContent> >(x => x.FirstOrDefault().RecipientData.RecipientType == RecipientDataType.Team)));
        }
        /// <summary>
        /// Create a new draft notification.
        /// </summary>
        /// <param name="notificationRepository">The notification repository.</param>
        /// <param name="notification">Draft Notification model class instance passed in from Web API.</param>
        /// <param name="userName">Name of the user who is running the application.</param>
        /// <returns>The newly created notification's id.</returns>
        public static async Task <string> CreateDraftNotificationAsync(
            this INotificationDataRepository notificationRepository,
            DraftNotification notification,
            string userName)
        {
            var newId = notificationRepository.TableRowKeyGenerator.CreateNewKeyOrderingOldestToMostRecent();

            var notificationEntity = new NotificationDataEntity
            {
                PartitionKey = NotificationDataTableNames.DraftNotificationsPartition,
                RowKey       = newId,
                Id           = newId,
                Title        = notification.Title,
                ImageLink    = notification.ImageLink,
                Summary      = notification.Summary,
                Author       = notification.Author,
                ButtonTitle  = notification.ButtonTitle,
                ButtonLink   = notification.ButtonLink,
                CreatedBy    = userName,
                CreatedDate  = DateTime.UtcNow,
                IsDraft      = true,
                Teams        = notification.Teams,
                Rosters      = notification.Rosters,
                Groups       = notification.Groups,
                AllUsers     = notification.AllUsers,
            };

            await notificationRepository.CreateOrUpdateAsync(notificationEntity);

            return(newId);
        }
예제 #3
0
        public async Task HandleFailureActivityNullArgumentTest()
        {
            // Arrange
            var activity = this.GetHandleFailureActivity();
            NotificationDataEntity notificationDataEntity = new NotificationDataEntity()
            {
                Id = "1",
            };

            this.notificationDataRepository
            .Setup(x => x.SaveExceptionInNotificationDataEntityAsync(It.IsAny <string>(), It.IsAny <string>()))
            .Returns(Task.CompletedTask);

            // Act
            Func <Task> task1 = async() => await activity.RunAsync((null /*notification*/, this.exception.Object));

            Func <Task> task2 = async() => await activity.RunAsync((notificationDataEntity, null /*excepion.*/));

            Func <Task> task3 = async() => await activity.RunAsync((null /*notification*/, null /*excepion.*/));

            // Assert
            await task1.Should().ThrowAsync <ArgumentNullException>("notification is null");

            await task2.Should().ThrowAsync <ArgumentNullException>("exception is null");

            await task3.Should().ThrowAsync <ArgumentNullException>("notification and excepion are null");

            this.notificationDataRepository.Verify(x => x.SaveExceptionInNotificationDataEntityAsync(It.Is <string>(x => x.Equals(notificationDataEntity.Id)), It.IsAny <string>()), Times.Never());
        }
        /// <summary>
        /// Send a preview of a draft notification.
        /// </summary>
        /// <param name="draftNotificationEntity">Draft notification entity.</param>
        /// <param name="teamDataEntity">The team data entity.</param>
        /// <param name="teamsChannelId">The Teams channel id.</param>
        /// <returns>It returns HttpStatusCode.OK, if this method triggers the bot service to send the adaptive card successfully.
        /// It returns HttpStatusCode.TooManyRequests, if the bot service throttled the request to send the adaptive card.</returns>
        public async Task <HttpStatusCode> SendPreview(NotificationDataEntity draftNotificationEntity, TeamDataEntity teamDataEntity, string teamsChannelId)
        {
            if (draftNotificationEntity == null)
            {
                throw new ArgumentException("Null draft notification entity.");
            }

            if (teamDataEntity == null)
            {
                throw new ArgumentException("Null team data entity.");
            }

            if (string.IsNullOrWhiteSpace(teamsChannelId))
            {
                throw new ArgumentException("Null channel id.");
            }

            // Create bot conversation reference.
            var conversationReference = this.PrepareConversationReferenceAsync(teamDataEntity, teamsChannelId);

            // Ensure the bot service URL is trusted.
            if (!MicrosoftAppCredentials.IsTrustedServiceUrl(conversationReference.ServiceUrl))
            {
                MicrosoftAppCredentials.TrustServiceUrl(conversationReference.ServiceUrl);
            }

            // Trigger bot to send the adaptive card.
            try
            {
                var previewQueueMessageContent = new SendQueueMessageContent
                {
                    NotificationId = draftNotificationEntity.Id,
                    ActivtiyId     = null,
                    RecipientData  = null,
                    NotificationUpdatePreviewEntity = new NotificationUpdatePreviewEntity
                    {
                        ActionType             = "PreviewNotification",
                        NotificationDataEntity = null,
                        ConversationReferance  = conversationReference,
                        MessageActivity        = await this.GetPreviewMessageActivity(draftNotificationEntity),
                        ServiceUrl             = conversationReference.ServiceUrl,
                        AppID = this.botAppId,
                    },
                };
                await this.sendQueue.SendAsync(previewQueueMessageContent);

                return(HttpStatusCode.OK);
            }
            catch (ErrorResponseException e)
            {
                var errorResponse = (ErrorResponse)e.Body;
                if (errorResponse != null &&
                    errorResponse.Error.Code.Equals(DraftNotificationPreviewService.ThrottledErrorResponse, StringComparison.OrdinalIgnoreCase))
                {
                    return(HttpStatusCode.TooManyRequests);
                }

                throw;
            }
        }
        public async Task UpdateDraftNotificationAsync([FromBody] DraftNotification notification)
        {
            var notificationEntity = new NotificationDataEntity
            {
                PartitionKey    = PartitionKeyNames.NotificationDataTable.DraftNotificationsPartition,
                RowKey          = notification.Id,
                Id              = notification.Id,
                Title           = notification.Title,
                ImageLink       = notification.ImageLink,
                Summary         = notification.Summary,
                Author          = notification.Author,
                ButtonTitle     = notification.ButtonTitle,
                ButtonLink      = notification.ButtonLink,
                ButtonTitle2    = notification.ButtonTitle2,
                ButtonLink2     = notification.ButtonLink2,
                CreatedBy       = this.HttpContext.User?.Identity?.Name,
                CreatedDate     = DateTime.UtcNow,
                IsDraft         = true,
                Teams           = notification.Teams,
                Rosters         = notification.Rosters,
                ADGroups        = notification.ADGroups,
                AllUsers        = notification.AllUsers,
                IsScheduled     = notification.IsScheduled,
                ScheduleDate    = notification.ScheduleDate,
                IsRecurrence    = notification.IsRecurrence,
                Repeats         = notification.Repeats,
                RepeatFor       = Convert.ToInt32(notification.RepeatFor),
                RepeatFrequency = notification.RepeatFrequency,
                WeekSelection   = notification.WeekSelection,
                RepeatStartDate = notification.RepeatStartDate,
                RepeatEndDate   = notification.RepeatEndDate,
            };

            await this.notificationDataRepository.CreateOrUpdateAsync(notificationEntity);
        }
        public async Task SendNotification_ForValidData_ReturnsStatusCodeOk()
        {
            // Arrange
            var controller        = this.GetControllerInstance();
            var draftNotification = new DraftNotification()
            {
                Id = "id"
            };
            var    sentNotificationId = "notificationId";
            string appId                  = null;
            var    teamsAppId             = "appId";
            var    statusCodeOk           = 200;
            var    notificationDataEntity = new NotificationDataEntity();

            this.notificationDataRepository.Setup(x => x.GetAsync(It.IsAny <string>(), It.IsAny <string>())).ReturnsAsync(notificationDataEntity);
            this.notificationDataRepository.Setup(x => x.MoveDraftToSentPartitionAsync(It.IsAny <NotificationDataEntity>())).ReturnsAsync(sentNotificationId);
            this.sentNotificationDataRepository.Setup(x => x.EnsureSentNotificationDataTableExistsAsync()).Returns(Task.CompletedTask);
            this.appSettingsService.Setup(x => x.GetUserAppIdAsync()).ReturnsAsync(appId);
            this.appSettingsService.Setup(x => x.SetUserAppIdAsync(It.IsAny <string>())).Returns(Task.CompletedTask);
            this.appCatalogService.Setup(x => x.GetTeamsAppIdAsync(It.IsAny <string>())).ReturnsAsync(teamsAppId);
            this.prepareToSendQueue.Setup(x => x.SendAsync(It.IsAny <PrepareToSendQueueMessageContent>())).Returns(Task.CompletedTask);
            this.dataQueue.Setup(x => x.SendDelayedAsync(It.IsAny <DataQueueMessageContent>(), It.IsAny <double>())).Returns(Task.CompletedTask);

            // Act
            var result = await controller.CreateSentNotificationAsync(draftNotification);

            var statusCode = ((StatusCodeResult)result).StatusCode;

            // Assert
            Assert.Equal(statusCode, statusCodeOk);
        }
예제 #7
0
        public async Task Get_GroupSearchServiceById_ReturnsOkObjectResult()
        {
            // Arrange
            var controller = this.GetGroupDataControllerInstance();
            var id         = "GroupId";
            var group      = new List <Group>()
            {
                new Group()
                {
                    Id = "Id", DisplayName = "name", Mail = "mail"
                },
            };
            var notificationDataEntity = new NotificationDataEntity()
            {
                Groups = new List <string>()
            };

            this.notificationDataRepository.Setup(x => x.GetAsync(It.IsAny <string>(), It.IsAny <string>())).ReturnsAsync(notificationDataEntity);
            this.groupsService.Setup(x => x.GetByIdsAsync(It.IsAny <IEnumerable <string> >())).Returns(group.ToAsyncEnumerable());

            // Act
            var result = await controller.GetGroupsAsync(id);

            // Assert
            Assert.IsType <OkObjectResult>(result.Result);
        }
        public async Task PrepareToSendOrchestratorSuccessWithReplayingFlagTrueTest()
        {
            // Arrange
            Mock <NotificationDataEntity> mockNotificationDataEntity = new Mock <NotificationDataEntity>();
            NotificationDataEntity        notificationDataEntity     = new NotificationDataEntity()
            {
                Id = "notificationId",
            };

            this.mockContext
            .Setup(x => x.IsReplaying)
            .Returns(true);

            this.mockContext
            .Setup(x => x.GetInput <NotificationDataEntity>())
            .Returns(notificationDataEntity);
            this.mockContext
            .Setup(x => x.CallActivityWithRetryAsync(It.IsAny <string>(), It.IsAny <RetryOptions>(), notificationDataEntity))
            .Returns(Task.CompletedTask);
            this.mockContext
            .Setup(x => x.CallSubOrchestratorWithRetryAsync(It.IsAny <string>(), It.IsAny <RetryOptions>(), notificationDataEntity))
            .Returns(Task.CompletedTask);

            // Act
            Func <Task> task = async() => await PrepareToSendOrchestrator.RunOrchestrator(this.mockContext.Object, this.mockLogger.Object);

            // Assert
            await task.Should().NotThrowAsync <Exception>();

            this.mockContext.Verify(x => x.CallActivityWithRetryAsync(It.Is <string>(x => x.Equals(FunctionNames.StoreMessageActivity)), It.IsAny <RetryOptions>(), It.IsAny <NotificationDataEntity>()), Times.Once());
            this.mockContext.Verify(x => x.CallSubOrchestratorWithRetryAsync(It.Is <string>(x => x.Equals(FunctionNames.SyncRecipientsOrchestrator)), It.IsAny <RetryOptions>(), It.IsAny <NotificationDataEntity>()), Times.Once());
            this.mockContext.Verify(x => x.CallSubOrchestratorWithRetryAsync(It.Is <string>(x => x.Equals(FunctionNames.TeamsConversationOrchestrator)), It.IsAny <RetryOptions>(), It.IsAny <NotificationDataEntity>()), Times.Once());
            this.mockContext.Verify(x => x.CallSubOrchestratorWithRetryAsync(It.Is <string>(x => x.Equals(FunctionNames.SendQueueOrchestrator)), It.IsAny <RetryOptions>(), It.IsAny <NotificationDataEntity>()), Times.Once());
        }
        public async Task SyncRecipientsOrchestratorGetAllUsersTest()
        {
            // Arrange
            NotificationDataEntity notificationDataEntity = new NotificationDataEntity()
            {
                Id       = "notificationId",
                AllUsers = true,
            };
            var recipientsInfo = new RecipientsInfo(notificationDataEntity.Id)
            {
                HasRecipientsPendingInstallation = true,
            };

            recipientsInfo.BatchKeys.Add("batchKey");

            this.mockContext
            .Setup(x => x.GetInput <NotificationDataEntity>())
            .Returns(notificationDataEntity);
            this.mockContext
            .Setup(x => x.CallActivityWithRetryAsync(It.IsAny <string>(), It.IsAny <RetryOptions>(), It.IsAny <object>()))
            .Returns(Task.CompletedTask);
            this.mockContext
            .Setup(x => x.CallActivityWithRetryAsync <RecipientsInfo>(It.IsAny <string>(), It.IsAny <RetryOptions>(), It.IsAny <NotificationDataEntity>()))
            .ReturnsAsync(recipientsInfo);

            // Act
            Func <Task> task = async() => await SyncRecipientsOrchestrator.RunOrchestrator(this.mockContext.Object, this.mockLogger.Object);

            // Assert
            await task.Should().NotThrowAsync <ArgumentException>();

            this.mockContext.Verify(x => x.CallActivityWithRetryAsync <RecipientsInfo>(It.Is <string>(x => x.Equals(FunctionNames.SyncAllUsersActivity)), It.IsAny <RetryOptions>(), It.Is <NotificationDataEntity>(x => x.AllUsers)), Times.Once); // All Users flag is true
            this.mockContext.Verify(x => x.CallActivityWithRetryAsync(It.Is <string>(x => x.Equals(FunctionNames.UpdateNotificationStatusActivity)), It.IsAny <RetryOptions>(), It.IsAny <object>()), Times.Once);
        }
        public async Task GetDraftSummaryConsent_ForValidData_ReturnsDraftSummaryForConsent()
        {
            // Arrange
            var controller             = this.GetDraftNotificationsController();
            var notificationDataEntity = new NotificationDataEntity()
            {
                TeamsInString   = "['team1','team2']",
                RostersInString = "['roster1','roster2']",
                GroupsInString  = "['group1','group2']",
                AllUsers        = true,
            };
            var groupList = new List <Group>()
            {
                new Group()
            };
            var teams = new List <string>()
            {
                "team1", "team2"
            };
            var rosters = new List <string>()
            {
                "roster1", "roster2"
            };

            this.notificationDataRepository.Setup(x => x.GetAsync(It.IsAny <string>(), It.IsAny <string>())).ReturnsAsync(notificationDataEntity);
            this.groupsService.Setup(x => x.GetByIdsAsync(It.IsAny <IEnumerable <string> >())).Returns(groupList.ToAsyncEnumerable());
            this.teamDataRepository.Setup(x => x.GetTeamNamesByIdsAsync(It.IsAny <IEnumerable <string> >())).ReturnsAsync(teams);
            this.teamDataRepository.Setup(x => x.GetTeamNamesByIdsAsync(It.IsAny <IEnumerable <string> >())).ReturnsAsync(rosters);

            // Act
            var result = await controller.GetDraftNotificationSummaryForConsentByIdAsync(this.notificationId);

            // Assert
            Assert.IsType <OkObjectResult>(result.Result);
        }
예제 #11
0
        public async Task <RecipientsInfo> RunAsync([ActivityTrigger] NotificationDataEntity notification, ILogger log)
        {
            if (notification == null)
            {
                throw new ArgumentNullException(nameof(notification));
            }

            // Sync all users.
            await this.SyncAllUsers(notification.Id);

            // Get users.
            var users = await this.userDataRepository.GetAllAsync();

            // This is to set UserType.
            await this.userTypeService.UpdateUserTypeForExistingUserListAsync(users);

            users = await this.userDataRepository.GetAllAsync();

            if (users.IsNullOrEmpty())
            {
                return(new RecipientsInfo(notification.Id));
            }

            // Store in sent notification table.
            var recipients = users.Select(
                user => user.CreateInitialSentNotificationDataEntity(partitionKey: notification.Id));

            await this.sentNotificationDataRepository.BatchInsertOrMergeAsync(recipients);

            // Store in batches and return batch info.
            return(await this.recipientsService.BatchRecipients(recipients));
        }
        public async Task SyncRecipientsOrchestratorGetAllUsersTest()
        {
            // Arrange
            NotificationDataEntity notificationDataEntity = new NotificationDataEntity()
            {
                Id       = "notificationId",
                AllUsers = true
            };

            mockContext
            .Setup(x => x.GetInput <NotificationDataEntity>())
            .Returns(notificationDataEntity);
            mockContext
            .Setup(x => x.CallActivityWithRetryAsync(It.IsAny <string>(), It.IsAny <RetryOptions>(), It.IsAny <object>()))
            .Returns(Task.CompletedTask);
            mockContext
            .Setup(x => x.CallActivityWithRetryAsync(It.IsAny <string>(), It.IsAny <RetryOptions>(), It.IsAny <NotificationDataEntity>()))
            .Returns(Task.CompletedTask);

            // Act
            Func <Task> task = async() => await SyncRecipientsOrchestrator.RunOrchestrator(mockContext.Object, mockLogger.Object);

            // Assert
            await task.Should().NotThrowAsync <ArgumentException>();

            mockContext.Verify(x => x.CallActivityWithRetryAsync(It.Is <string>(x => x.Equals(FunctionNames.SyncAllUsersActivity)), It.IsAny <RetryOptions>(),
                                                                 It.Is <NotificationDataEntity>(x => x.AllUsers))); // Allusers flag is true
            mockContext.Verify(x => x.CallActivityWithRetryAsync(It.Is <string>(x => x.Equals(FunctionNames.UpdateNotificationStatusActivity)), It.IsAny <RetryOptions>(), It.IsAny <object>()));
        }
        public async Task SyncRecipientsOrchestratorGetMembersOfSpecifictTeamTest()
        {
            // Arrange
            NotificationDataEntity notificationDataEntity = new NotificationDataEntity()
            {
                Id       = "notificationId",
                AllUsers = false,
                Rosters  = new List <string>()
                {
                    "roaster", "roaster1"
                }
            };

            mockContext
            .Setup(x => x.GetInput <NotificationDataEntity>())
            .Returns(notificationDataEntity);
            mockContext
            .Setup(x => x.CallActivityWithRetryAsync(It.IsAny <string>(), It.IsAny <RetryOptions>(), It.IsAny <object>()))
            .Returns(Task.CompletedTask);

            // Act
            Func <Task> task = async() => await SyncRecipientsOrchestrator.RunOrchestrator(mockContext.Object, mockLogger.Object);

            // Assert
            await task.Should().NotThrowAsync <ArgumentException>();

            mockContext.Verify(x => x.CallActivityWithRetryAsync(It.Is <string>(x => x.Equals(FunctionNames.SyncTeamMembersActivity)), It.IsAny <RetryOptions>()
                                                                 , It.IsAny <object>()), Times.Exactly(notificationDataEntity.Rosters.Count()));
        }
 /// <summary>
 /// Checks if the notification is completed.
 ///
 /// Note: we check the IsCompleted property for backward compatibility. (Data generated for CC v1, v2).
 /// </summary>
 /// <param name="entity">Notification data entity.</param>
 /// <returns>If the notification is completed.</returns>
 public static bool IsCompleted(this NotificationDataEntity entity)
 {
     return(NotificationStatus.Failed.ToString().Equals(entity.Status) ||
            NotificationStatus.Sent.ToString().Equals(entity.Status) ||
            NotificationStatus.Canceled.ToString().Equals(entity.Status) ||
            entity.IsCompleted);
 }
예제 #15
0
        public async Task SyncTeamsActivityNullArgumentTest()
        {
            // Arrange
            var activityContext = this.GetSyncTamActivity();
            NotificationDataEntity notification = new NotificationDataEntity()
            {
                Id = "notificationId",
            };
            IEnumerable <TeamDataEntity> teamData = new List <TeamDataEntity>();

            this.teamDataRepository.Setup(x => x.GetTeamDataEntitiesByIdsAsync(It.IsAny <IEnumerable <string> >())).ReturnsAsync(teamData);

            // Act
            Func <Task> task1 = async() => await activityContext.RunAsync(null /*notification*/, null /*logger*/);

            Func <Task> task2 = async() => await activityContext.RunAsync(null /*notification*/, this.log.Object);

            Func <Task> task3 = async() => await activityContext.RunAsync(notification, null /*logger*/);

            // Assert
            await task1.Should().ThrowAsync <ArgumentNullException>();

            await task2.Should().ThrowAsync <ArgumentNullException>("notification is null");

            await task3.Should().ThrowAsync <ArgumentNullException>("logger is null");
        }
예제 #16
0
        public async Task RunAsync(
            [ActivityTrigger] NotificationDataEntity notification)
        {
            if (notification == null)
            {
                throw new ArgumentNullException(nameof(notification));
            }

            var templateID          = notification.TemplateID;
            var templateDataforcard = await this.templateDataRepository.GetAsync("Default", templateID);

            var serializedContent = string.Empty;

            serializedContent = this.adaptiveCardCreator.CreateAdaptiveCardWithoutHeader(notification, templateDataforcard.TemplateJSON);

            var sendingNotification = new SendingNotificationDataEntity
            {
                PartitionKey   = NotificationDataTableNames.SendingNotificationsPartition,
                RowKey         = notification.RowKey,
                NotificationId = notification.Id,
                Channel        = notification.Channel,
                TemplateID     = notification.TemplateID,
                Content        = serializedContent,
            };

            await this.sendingNotificationDataRepository.CreateOrUpdateAsync(sendingNotification);
        }
        public async Task DataAggregationTriggerActivitySuccessTest()
        {
            // Arrange
            var                    dataAggregationTriggerActivity = this.GetDataAggregationTriggerActivity();
            var                    notificationId   = "notificationId1";
            var                    recipientCount   = 1;
            Mock <ILogger>         logger           = new Mock <ILogger>();
            NotificationDataEntity notificationData = new NotificationDataEntity()
            {
                Id = notificationId
            };

            notificationDataRepository
            .Setup(x => x.GetAsync(It.IsAny <string>(), It.IsAny <string>()))
            .ReturnsAsync(notificationData);
            notificationDataRepository
            .Setup(x => x.CreateOrUpdateAsync(It.IsAny <NotificationDataEntity>()))
            .Returns(Task.CompletedTask);
            dataQueue
            .Setup(x => x.SendDelayedAsync(It.IsAny <DataQueueMessageContent>(), It.IsAny <double>()))
            .Returns(Task.CompletedTask);

            // Act
            Func <Task> task = async() => await dataAggregationTriggerActivity.RunAsync((notificationId, recipientCount), logger.Object);

            // Assert
            await task.Should().NotThrowAsync();

            notificationDataRepository.Verify(x => x.GetAsync(It.IsAny <string>(), It.Is <string>(x => x.Equals(notificationId))), Times.Once());
            notificationDataRepository.Verify(x => x.CreateOrUpdateAsync(It.Is <NotificationDataEntity>(x => x.TotalMessageCount == recipientCount)));
            dataQueue.Verify(x => x.SendDelayedAsync(It.Is <DataQueueMessageContent>(x => x.NotificationId == notificationId), It.Is <double>(x => x.Equals(messageDelayInSeconds))));
        }
        public async Task StoreMessageActivitySuccessTest()
        {
            // Arrange
            NotificationDataEntity notification = new NotificationDataEntity()
            {
                Id = "123"
            };
            var          activityContext = GetStoreMessageActivity();
            AdaptiveCard adaptiveCard    = new AdaptiveCard();

            adaptiveCardCreator
            .Setup(x => x.CreateAdaptiveCard(It.IsAny <NotificationDataEntity>()))
            .Returns(adaptiveCard);
            sendingNotificationDataRepository
            .Setup(x => x.CreateOrUpdateAsync(It.IsAny <SendingNotificationDataEntity>()))
            .Returns(Task.CompletedTask);

            // Act
            Func <Task> task = async() => await activityContext.RunAsync(notification);

            // Assert
            await task.Should().NotThrowAsync();

            adaptiveCardCreator.Verify(x => x.CreateAdaptiveCard(It.Is <NotificationDataEntity>(x => x.Id == notification.Id)));
            sendingNotificationDataRepository.Verify(x => x.CreateOrUpdateAsync(It.Is <SendingNotificationDataEntity>(x => x.NotificationId == notification.Id)));
        }
예제 #19
0
        public async Task SyncAllUsers_AllGuestUsersFromDB_ShouldBeSavedInTable()
        {
            // Arrange
            var    activityContext = this.GetSyncAllUsersActivity();
            string deltaLink       = "deltaLink";
            IEnumerable <UserDataEntity> userDataResponse = new List <UserDataEntity>()
            {
                new UserDataEntity()
                {
                    Name = "user1", UserType = UserType.Member
                },
                new UserDataEntity()
                {
                    Name = "user2", UserType = UserType.Guest
                },
            };
            NotificationDataEntity notification = new NotificationDataEntity()
            {
                Id = "notificationId1",
            };

            (IEnumerable <User>, string)tuple = (new List <User>()
            {
                new User()
                {
                    Id = "101", UserType = "Guest"
                }
            }, deltaLink);
            this.userDataRepository
            .Setup(x => x.GetDeltaLinkAsync())
            .ReturnsAsync(deltaLink);
            this.userService
            .Setup(x => x.GetAllUsersAsync(It.IsAny <string>()))
            .ReturnsAsync(tuple);

            this.userDataRepository
            .Setup(x => x.SetDeltaLinkAsync(It.IsAny <string>()))
            .Returns(Task.CompletedTask);
            this.userDataRepository
            .Setup(x => x.GetAllAsync(It.IsAny <string>(), null))
            .ReturnsAsync(userDataResponse);
            this.userTypeService
            .Setup(x => x.UpdateUserTypeForExistingUserListAsync(It.IsAny <IEnumerable <UserDataEntity> >()))
            .Returns(Task.CompletedTask);

            // store user data
            this.userDataRepository
            .Setup(x => x.InsertOrMergeAsync(It.IsAny <UserDataEntity>()))
            .Returns(Task.CompletedTask);
            this.sentNotificationDataRepository.Setup(x => x.BatchInsertOrMergeAsync(It.IsAny <IEnumerable <SentNotificationDataEntity> >()));

            // Act
            Func <Task> task = async() => await activityContext.RunAsync(notification, this.logger.Object);

            // Assert
            await task.Should().NotThrowAsync();

            this.sentNotificationDataRepository.Verify(x => x.BatchInsertOrMergeAsync(It.Is <IEnumerable <SentNotificationDataEntity> >(l => l.Count() == 2)), Times.Once);
            this.recipientsService.Verify(x => x.BatchRecipients(It.IsAny <IEnumerable <SentNotificationDataEntity> >()), Times.Once);
        }
        public async Task ExportFunctionRunSuccessTest()
        {
            // Arrange
            var    activityInstance = GetExportFunction();
            string messageContent   = "{\"NotificationId\":\"notificationId\",\"UserId\" : \"userId\"}";
            var    notificationdata = new NotificationDataEntity();
            var    exportDataEntity = new ExportDataEntity();

            notificationDataRepository
            .Setup(x => x.GetAsync(It.IsAny <string>(), It.IsAny <string>()))
            .ReturnsAsync(notificationdata);
            exportDataRepository
            .Setup(x => x.GetAsync(It.IsAny <string>(), It.IsAny <string>()))
            .ReturnsAsync(exportDataEntity);

            starter.Setup(x => x.StartNewAsync(It.IsAny <string>(), It.IsAny <string>())).ReturnsAsync(It.IsAny <string>);

            // Act
            Func <Task> task = async() => await activityInstance.Run(messageContent, starter.Object);

            // Assert
            await task.Should().NotThrowAsync();

            notificationDataRepository.Verify(x => x.GetAsync(It.IsAny <string>(), It.Is <string>(x => x.Equals("notificationId"))), Times.Once());
            exportDataRepository.Verify(x => x.GetAsync(It.IsAny <string>(), It.Is <string>(x => x.Equals("notificationId"))), Times.Once());
        }
        public async Task SyncRecipientsOrchestratorGetMembersOfGeneralChannelTest()
        {
            // Arrange
            NotificationDataEntity notificationDataEntity = new NotificationDataEntity()
            {
                Id       = "notificationId",
                AllUsers = false,
                Rosters  = new List <string>(),
                Groups   = new List <string>(),
                Teams    = new List <string>()
                {
                    "TestTeamChannel"
                },
            };

            this.mockContext
            .Setup(x => x.GetInput <NotificationDataEntity>())
            .Returns(notificationDataEntity);
            this.mockContext
            .Setup(x => x.CallActivityWithRetryAsync(It.IsAny <string>(), It.IsAny <RetryOptions>(), It.IsAny <object>()))
            .Returns(Task.CompletedTask);

            // Act
            Func <Task> task = async() => await SyncRecipientsOrchestrator.RunOrchestrator(this.mockContext.Object, this.mockLogger.Object);

            // Assert
            await task.Should().NotThrowAsync <ArgumentException>();

            this.mockContext
            .Verify(x => x.CallActivityWithRetryAsync <RecipientsInfo>(It.Is <string>(x => x.Equals(FunctionNames.SyncTeamsActivity)), It.IsAny <RetryOptions>(), It.IsAny <object>()), Times.Exactly(1));
            this.mockContext.Verify(x => x.CallActivityWithRetryAsync(It.Is <string>(x => x.Equals(FunctionNames.UpdateNotificationStatusActivity)), It.IsAny <RetryOptions>(), It.IsAny <object>()), Times.Once);
        }
        private IMessageActivity CreateReply(NotificationDataEntity notificationDataEntity, string templateJson)
        {
            var adaptiveCard = this.adaptiveCardCreator.CreateAdaptiveCardWithoutHeader(
                notificationDataEntity.Title,
                notificationDataEntity.ImageLink,
                notificationDataEntity.Summary,
                notificationDataEntity.Author,
                notificationDataEntity.ButtonTitle,
                notificationDataEntity.ButtonLink,
                templateJson);

            /*var adaptiveCard = this.adaptiveCardCreator.CreateAdaptiveCard(
             *     "Testing3",
             *     "https://www.cloudsavvyit.com/thumbcache/600/340/dc6262cc4d1f985b23e2bca456d9a611/p/uploads/2020/09/8b1648fb.png",
             *     "Summary Test",
             *     "Test",
             *     "Click here",
             *     "https://clickhere.com"
             *     );*/

            var attachment = new Attachment
            {
                ContentType = AdaptiveCard.ContentType,
                Content     = adaptiveCard,
            };

            var reply = MessageFactory.Attachment(attachment);

            return(reply);
        }
        public async Task Get_SetUserAppIdServiceCall_ShouldInvokedOnce()
        {
            // Arrange
            var controller        = this.GetControllerInstance();
            var draftNotification = new DraftNotification()
            {
                Id = "id"
            };
            var    sentNotificationId = "notificationId";
            string appId                  = null;
            var    teamsAppId             = "appId";
            var    notificationDataEntity = new NotificationDataEntity();

            this.notificationDataRepository.Setup(x => x.GetAsync(It.IsAny <string>(), It.IsAny <string>())).ReturnsAsync(notificationDataEntity);
            this.notificationDataRepository.Setup(x => x.MoveDraftToSentPartitionAsync(It.IsAny <NotificationDataEntity>())).ReturnsAsync(sentNotificationId);
            this.sentNotificationDataRepository.Setup(x => x.EnsureSentNotificationDataTableExistsAsync()).Returns(Task.CompletedTask);
            this.appSettingsService.Setup(x => x.GetUserAppIdAsync()).ReturnsAsync(appId);
            this.appSettingsService.Setup(x => x.SetUserAppIdAsync(It.IsAny <string>())).Returns(Task.CompletedTask);
            this.appCatalogService.Setup(x => x.GetTeamsAppIdAsync(It.IsAny <string>())).ReturnsAsync(teamsAppId);

            // Act
            await controller.CreateSentNotificationAsync(draftNotification);

            // Assert
            this.appSettingsService.Verify(x => x.SetUserAppIdAsync(It.IsAny <string>()), Times.Once());
        }
        public async Task SendBatchMessagesActivityFailureTest()
        {
            // Arrange
            var activity = this.GetSendBatchMessagesActivity();
            List <SentNotificationDataEntity> batch = new List <SentNotificationDataEntity>()
            {
                new SentNotificationDataEntity()
                {
                    RecipientType = SentNotificationDataEntity.TeamRecipientType,
                    RecipientId   = "recipientId",
                },
            };
            NotificationDataEntity notification = new NotificationDataEntity()
            {
                Id = "notificationId",
            };

            // Act
            Func <Task> task1 = async() => await activity.RunAsync((notification.Id, null /*batch*/));

            Func <Task> task2 = async() => await activity.RunAsync((null /*notification*/, batch));

            Func <Task> task3 = async() => await activity.RunAsync((null /*notification*/, null /*batch*/));

            // Assert
            await task1.Should().ThrowAsync <ArgumentNullException>("batch is null");

            await task2.Should().ThrowAsync <ArgumentNullException>("notification is null");

            await task3.Should().ThrowAsync <ArgumentNullException>("notification and batch are null");
        }
 /// <summary>
 /// Send an adaptive card when bot trigger.
 /// </summary>
 /// <param name="turnContext">The context object for this turn.</param>
 /// <param name="draftNotificationEntity">Data for notifications that are either (depending on partition key):drafts,sent.</param>
 /// <returns>Return adaptive card as notification.</returns>
 private async Task SendAdaptiveCardAsync(
     ITurnContext turnContext,
     NotificationDataEntity draftNotificationEntity)
 {
     var reply = this.CreateReply(draftNotificationEntity);
     await turnContext.SendActivityAsync(reply);
 }
예제 #26
0
        public async Task SyncRecipientsOrchestratorForInvalidAudienceSelectionTest()
        {
            // Arrange
            NotificationDataEntity notificationDataEntity = new NotificationDataEntity()
            {
                Id       = "notificationId",
                AllUsers = false,
                Rosters  = new List <string>(),
                Groups   = new List <string>(),
                Teams    = new List <string>(),
                CsvUsers = string.Empty,
            };

            this.mockContext.Setup(x => x.GetInput <NotificationDataEntity>()).Returns(notificationDataEntity);
            this.mockContext.Setup(x => x.CallActivityWithRetryAsync(It.IsAny <string>(), It.IsAny <RetryOptions>(), It.IsAny <object>()))
            .Returns(Task.CompletedTask);

            // Act
            Func <Task> task = async() => await SyncRecipientsOrchestrator.RunOrchestrator(this.mockContext.Object, this.mockLogger.Object);

            // Assert
            await task.Should().ThrowAsync <ArgumentException>($"Invalid audience select for notification id: {notificationDataEntity.Id}");

            this.mockContext.Verify(x => x.CallActivityWithRetryAsync(It.Is <string>(x => x.Equals(FunctionNames.UpdateNotificationStatusActivity)), It.IsAny <RetryOptions>(), It.IsAny <object>()), Times.Once);
        }
예제 #27
0
        public async Task <RecipientsInfo> RunAsync([ActivityTrigger] NotificationDataEntity notification, ILogger log)
        {
            if (notification == null)
            {
                throw new ArgumentNullException(nameof(notification));
            }

            log.LogDebug("About to process the list of CSV users.");
            log.LogDebug("notification.CsvUsers: " + notification.CsvUsers);

            // sync users from the csv file
            List <User> users         = new List <User>();
            string      strtp         = notification.CsvUsers.Substring(2, notification.CsvUsers.Length - 4);
            var         csvUsersArray = strtp.Split(",");

            string usertp;
            User   usr;

            foreach (string userst in csvUsersArray)
            {
                if (!userst.IsNullOrEmpty())
                {
                    usertp = userst.Substring(1, userst.Length - 2);
                    log.LogDebug("Processing: " + usertp);

                    try
                    {
                        usr = await this.usersService.GetUserAsync(usertp);

                        users.Add(usr);
                        log.LogDebug("User " + usertp + " added to the collection.");
                    }
                    catch (Exception ex)
                    {
                        log.LogError("User not added to the collection.");
                        log.LogError("User " + usertp + " is invalid. " + ex.Message);
                    }
                }
            }

            log.LogDebug("About to convert to recipients.");

            // Convert to Recipients
            var recipients = await this.GetRecipientsAsync(notification.Id, users);

            log.LogDebug("CSV Users converted to recipients.");

            log.LogDebug("About to store the list of recipients on the database.");

            // Store.
            await this.sentNotificationDataRepository.BatchInsertOrMergeAsync(recipients);

            log.LogDebug("Sent messages stored on the database for future updates.");

            log.LogDebug("Finished. Batching recipients and moving to the next pipeline step.");

            // Store in batches and return batch info.
            return(await this.recipientsService.BatchRecipients(recipients));
        }
예제 #28
0
        private async Task <string> GetActivityIDandLikes(NotificationDataEntity notificationEntity)
        {
            // var tenantId = this.HttpContext.User.FindFirstValue(Common.Constants.ClaimTypeTenantId);
            // var serviceUrl = await this.appSettingsService.GetServiceUrlAsync();
            int likes     = 0;
            int likeCount = 0;

            try
            {
                var channelDataEntity = await this.channelDataRepository.GetFilterAsync("RowKey eq '" + notificationEntity.Channel + "'", null);

                foreach (ChannelDataEntity channelData in channelDataEntity)
                {
                    this.account = channelData.ChannelName;
                }

                var sentNotificationEntities = await this.sentNotificationDataRepstry.GetActivityIDAsync(notificationEntity.RowKey);

                foreach (var sentNotificationEntity in sentNotificationEntities)
                {
                    if (sentNotificationEntity != null && !string.IsNullOrEmpty(sentNotificationEntity.ConversationId))
                    {
                        var teamsDataEntity = await this.teamDataRepository.GetWithFilterAsync("RowKey eq '" + sentNotificationEntity.ConversationId + "'");

                        if (teamsDataEntity != null && teamsDataEntity.ToArray().Length > 0)
                        {
                            foreach (var teamsData in teamsDataEntity)
                            {
                                string teamsID = await this.groupsService.SearchTeamsGroupAsync("displayname eq '" + teamsData.Name + "'");

                                if (!string.IsNullOrEmpty(teamsID))
                                {
                                    var messageResponse = await this.reactionService.GetMessagesAsync(teamsID, sentNotificationEntity.ConversationId, sentNotificationEntity.ActivtyId);

                                    if (messageResponse != null && messageResponse.Reactions != null && messageResponse.Reactions.ToArray().Length > 0)
                                    {
                                        foreach (var reaction in messageResponse.Reactions)
                                        {
                                            if (reaction.ReactionType.ToString() == "like")
                                            {
                                                likeCount++;
                                            }
                                        }

                                        likes = likeCount;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
            }

            return(likes.ToString());
        }
예제 #29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ExportDataRequirement"/> class.
 /// </summary>
 /// <param name="notificationDataEntity">the notification data entity.</param>
 /// <param name="exportDataEntity">the export data entity.</param>
 /// <param name="userId">user id.</param>
 public ExportDataRequirement(
     NotificationDataEntity notificationDataEntity,
     ExportDataEntity exportDataEntity,
     string userId)
 {
     this.NotificationDataEntity = notificationDataEntity;
     this.ExportDataEntity       = exportDataEntity;
     this.UserId = userId;
 }
 /// <summary>
 /// Run the activity.
 /// </summary>
 /// <param name="context">Durable orchestration context.</param>
 /// <param name="notificationDataEntity">Notification data entity.</param>
 /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
 public async Task RunAsync(
     IDurableOrchestrationContext context,
     NotificationDataEntity notificationDataEntity)
 {
     await context.CallActivityWithRetryAsync(
         nameof(CreateSendingNotificationActivity.CreateSendingNotificationAsync),
         ActivitySettings.CommonActivityRetryOptions,
         notificationDataEntity);
 }