Пример #1
0
 public PurchaseBookSubscriber(ILogger <PurchaseBookSubscriber> logger,
                               IOptions <RetrySetting> retrySetting,
                               ISubscriber <PurchaseBookRedisModel> subscriber)
     : base(logger, subscriber)
 {
     _retrySetting = retrySetting.Value;
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="MSGraphNotificationProvider"/> class.
        /// </summary>
        /// <param name="configuration">Instance of <see cref="IConfiguration"/>.</param>
        /// <param name="emailAccountManager">Instance of <see cref="IEmailAccountManager"/>.</param>
        /// <param name="logger">Instance of <see cref="ILogger"/>.</param>
        /// <param name="mSGraphSetting">Instance of <see cref="IEmailManager"/>.</param>
        /// <param name="pollyRetrySetting">Instance of <see cref="RetrySetting"/>.</param>
        /// <param name="tokenHelper">Instance of <see cref="ITokenHelper"/>.</param>
        /// <param name="msGraphProvider">Instance of <see cref="IMSGraphProvider"/>.</param>
        /// <param name="emailManager">Instance of <see cref="IEmailManager"/>..</param>
        public MSGraphNotificationProvider(
            IConfiguration configuration,
            IEmailAccountManager emailAccountManager,
            ILogger logger,
            IOptions <MSGraphSetting> mSGraphSetting,
            IOptions <RetrySetting> pollyRetrySetting,
            ITokenHelper tokenHelper,
            IMSGraphProvider msGraphProvider,
            IEmailManager emailManager)
        {
            this.configuration       = configuration;
            this.applicationAccounts = JsonConvert.DeserializeObject <List <ApplicationAccounts> >(this.configuration?["ApplicationAccounts"]);
            this.emailAccountManager = emailAccountManager;
            this.logger = logger;
            _           = int.TryParse(this.configuration["RetrySetting:MaxRetries"], out this.maxTryCount);
            if (this.configuration?["MailSettings"] != null)
            {
                this.mailSettings = JsonConvert.DeserializeObject <List <MailSettings> >(this.configuration?["MailSettings"]);
            }

            this.mSGraphSetting         = mSGraphSetting?.Value;
            this.pollyRetrySetting      = pollyRetrySetting?.Value;
            this.jsonSerializerSettings = new JsonSerializerSettings
            {
                ContractResolver  = new Newtonsoft.Json.Serialization.DefaultContractResolver(),
                NullValueHandling = NullValueHandling.Ignore,
            };
            this.tokenHelper     = tokenHelper;
            this.msGraphProvider = msGraphProvider;
            this.emailManager    = emailManager;
        }
Пример #3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MSGraphProvider"/> class.
 /// </summary>
 /// <param name="mSGraphSetting">MS Graph Settings from configuration.</param>
 /// <param name="pollyRetrySetting">Polly Retry Settings.</param>
 /// <param name="logger">Instance of Logger.</param>
 /// <param name="httpClient">Http Client.</param>
 public MSGraphProvider(IOptions <MSGraphSetting> mSGraphSetting, IOptions <RetrySetting> pollyRetrySetting, ILogger logger, HttpClient httpClient)
 {
     this.jsonSerializerSettings = new JsonSerializerSettings
     {
         Converters = new List <JsonConverter> {
             new StringEnumConverter()
         },
         ContractResolver  = new Newtonsoft.Json.Serialization.DefaultContractResolver(),
         NullValueHandling = NullValueHandling.Ignore,
     };
     this.mSGraphSetting    = mSGraphSetting?.Value;
     this.pollyRetrySetting = pollyRetrySetting?.Value;
     this.logger            = logger;
     this.httpClient        = httpClient;
 }
Пример #4
0
        public void SendEmailNotificationsTestRequeueForTransientErrors()
        {
            this.MsGraphSetting.Value.EnableBatching = false;
            EmailNotificationItem[] notificationItems = new EmailNotificationItem[]
            {
                new EmailNotificationItem()
                {
                    To = "*****@*****.**", Subject = "TestSubject", Body = "TestBody", NotificationId = "1"
                },
                new EmailNotificationItem()
                {
                    To = "*****@*****.**", Subject = "TestSubject", Body = "TestBody", NotificationId = "2"
                },
            };

            IList <EmailNotificationItemEntity> emailNotificationItemEntities = new List <EmailNotificationItemEntity>()
            {
                new EmailNotificationItemEntity()
                {
                    Application    = this.ApplicationName,
                    NotificationId = "1",
                    To             = "*****@*****.**",
                    Subject        = "TestEmailSubject",
                    Body           = "CfDJ8KvR5DP4DK5GqV1jviPzBnsv3onVDZ-ztz-AvRl_6nvVNg86jfmKjgySREDPW9xNrwpKALT5BIFNX6VK3wzKsxc51dbkQjPPG9l7436wQktrAMRadumTpGKNKG1lLlP0FA",
                    Id             = "1",
                },
                new EmailNotificationItemEntity()
                {
                    Application    = this.ApplicationName,
                    NotificationId = "2",
                    To             = "*****@*****.**",
                    Subject        = "TestEmailSubject",
                    Body           = "CfDJ8KvR5DP4DK5GqV1jviPzBnsv3onVDZ-ztz-AvRl_6nvVNg86jfmKjgySREDPW9xNrwpKALT5BIFNX6VK3wzKsxc51dbkQjPPG9l7436wQktrAMRadumTpGKNKG1lLlP0FA",
                    Id             = "2",
                },
            };

            var retrySetting = new RetrySetting
            {
                MaxRetries          = 10,
                TransientRetryCount = 3,
            };

            _ = this.EmailNotificationRepository
                .Setup(repository => repository.GetRepository(StorageType.StorageAccount).GetEmailNotificationItemEntities(It.IsAny <IList <string> >(), It.IsAny <string>()))
                .Returns(Task.FromResult(emailNotificationItemEntities));

            // Test the transient error: Too many Requests/ Request Timeout
            var graphProvider = new Mock <IMSGraphProvider>();

            _ = graphProvider
                .Setup(gp => gp.SendEmailNotification(It.IsAny <AuthenticationHeaderValue>(), It.IsAny <EmailMessagePayload>(), It.IsAny <string>()))
                .Returns(Task.FromResult(false));

            _ = this.TokenHelper
                .Setup(th => th.GetAuthenticationHeaderValueForSelectedAccount(It.IsAny <AccountCredential>()))
                .ReturnsAsync(new AuthenticationHeaderValue(ApplicationConstants.BearerAuthenticationScheme, "Test"));

            this.MSGraphNotificationProvider = new MSGraphNotificationProvider(this.Configuration, this.EmailAccountManager.Object, this.Logger, this.MsGraphSetting, this.TokenHelper.Object, graphProvider.Object, this.EmailManager);

            _ = this.NotificationProviderFactory
                .Setup(provider => provider.GetNotificationProvider(NotificationProviderType.Graph))
                .Returns(this.MSGraphNotificationProvider);

            var emailServiceManager = new EmailServiceManager(this.Configuration, this.EmailNotificationRepository.Object, this.CloudStorageClient.Object, this.Logger, this.NotificationProviderFactory.Object, this.EmailManager);

            Task <IList <NotificationResponse> > result = emailServiceManager.SendEmailNotifications(this.ApplicationName, notificationItems);

            Assert.AreEqual(result.Status.ToString(), "RanToCompletion");
            Assert.AreEqual(result.Result.Count(x => x.Status == NotificationItemStatus.Retrying), notificationItems.Count());
            this.EmailNotificationRepository.Verify(repo => repo.GetRepository(StorageType.StorageAccount).UpdateEmailNotificationItemEntities(It.IsAny <IList <EmailNotificationItemEntity> >()), Times.Once);
            this.CloudStorageClient.Verify(csa => csa.QueueCloudMessages(It.IsAny <CloudQueue>(), It.IsAny <IEnumerable <string> >(), null), Times.Once);

            // When Graph calls succeed
            _ = graphProvider
                .Setup(gp => gp.SendEmailNotification(It.IsAny <AuthenticationHeaderValue>(), It.IsAny <EmailMessagePayload>(), It.IsAny <string>()))
                .Returns(Task.FromResult(true));

            emailServiceManager = new EmailServiceManager(this.Configuration, this.EmailNotificationRepository.Object, this.CloudStorageClient.Object, this.Logger, this.NotificationProviderFactory.Object, this.EmailManager);

            result = emailServiceManager.SendEmailNotifications(this.ApplicationName, notificationItems);
            Assert.AreEqual(result.Status.ToString(), "RanToCompletion");
            Assert.AreEqual(result.Result.Count(x => x.Status == NotificationItemStatus.Sent), notificationItems.Count());

            this.EmailNotificationRepository.Verify(repo => repo.GetRepository(StorageType.StorageAccount).UpdateEmailNotificationItemEntities(It.IsAny <IList <EmailNotificationItemEntity> >()), Times.Exactly(2));

            // This is called when retrying the transient failed items previously, count not changed
            this.CloudStorageClient.Verify(csa => csa.QueueCloudMessages(It.IsAny <CloudQueue>(), It.IsAny <IEnumerable <string> >(), null), Times.Once);

            // When graph call throws exception
            _ = graphProvider
                .Setup(gp => gp.SendEmailNotification(It.IsAny <AuthenticationHeaderValue>(), It.IsAny <EmailMessagePayload>(), It.IsAny <string>()))
                .ThrowsAsync(new AggregateException());

            emailServiceManager = new EmailServiceManager(this.Configuration, this.EmailNotificationRepository.Object, this.CloudStorageClient.Object, this.Logger, this.NotificationProviderFactory.Object, this.EmailManager);

            result = emailServiceManager.SendEmailNotifications(this.ApplicationName, notificationItems);
            Assert.AreEqual(result.Status.ToString(), "RanToCompletion");
            Assert.AreEqual(result.Result.Count(x => x.Status == NotificationItemStatus.Failed), notificationItems.Count());

            this.EmailNotificationRepository.Verify(repo => repo.GetRepository(StorageType.StorageAccount).UpdateEmailNotificationItemEntities(It.IsAny <IList <EmailNotificationItemEntity> >()), Times.Exactly(3));

            // This is called when retrying the transient failed items previously, count not changed
            this.CloudStorageClient.Verify(csa => csa.QueueCloudMessages(It.IsAny <CloudQueue>(), It.IsAny <IEnumerable <string> >(), null), Times.Once);

            Assert.Pass();
        }
Пример #5
0
        public void SendEmailNotificationsInBatchTestRequeueForTransientErrors()
        {
            this.MsGraphSetting.Value.EnableBatching = true;
            EmailNotificationItem[] notificationItems = new EmailNotificationItem[]
            {
                new EmailNotificationItem()
                {
                    To = "*****@*****.**", Subject = "TestSubject", Body = "TestBody", NotificationId = "1"
                },
                new EmailNotificationItem()
                {
                    To = "*****@*****.**", Subject = "TestSubject", Body = "TestBody", NotificationId = "2"
                },
                new EmailNotificationItem()
                {
                    To = "*****@*****.**", Subject = "TestSubject", Body = "TestBody", NotificationId = "3"
                },
            };

            IList <EmailNotificationItemEntity> emailNotificationItemEntities = new List <EmailNotificationItemEntity>()
            {
                new EmailNotificationItemEntity()
                {
                    Application    = this.ApplicationName,
                    NotificationId = "1",
                    To             = "*****@*****.**",
                    Subject        = "TestEmailSubject",
                    Body           = "CfDJ8KvR5DP4DK5GqV1jviPzBnsv3onVDZ-ztz-AvRl_6nvVNg86jfmKjgySREDPW9xNrwpKALT5BIFNX6VK3wzKsxc51dbkQjPPG9l7436wQktrAMRadumTpGKNKG1lLlP0FA",
                    Id             = "1",
                },
                new EmailNotificationItemEntity()
                {
                    Application    = this.ApplicationName,
                    NotificationId = "2",
                    To             = "*****@*****.**",
                    Subject        = "TestEmailSubject",
                    Body           = "CfDJ8KvR5DP4DK5GqV1jviPzBnsv3onVDZ-ztz-AvRl_6nvVNg86jfmKjgySREDPW9xNrwpKALT5BIFNX6VK3wzKsxc51dbkQjPPG9l7436wQktrAMRadumTpGKNKG1lLlP0FA",
                    Id             = "2",
                },
                new EmailNotificationItemEntity()
                {
                    Application    = this.ApplicationName,
                    NotificationId = "3",
                    To             = "*****@*****.**",
                    Subject        = "TestEmailSubject",
                    Body           = "CfDJ8KvR5DP4DK5GqV1jviPzBnsv3onVDZ-ztz-AvRl_6nvVNg86jfmKjgySREDPW9xNrwpKALT5BIFNX6VK3wzKsxc51dbkQjPPG9l7436wQktrAMRadumTpGKNKG1lLlP0FA",
                    Id             = "3",
                },
            };
            var retrySetting = new RetrySetting
            {
                MaxRetries          = 10,
                TransientRetryCount = 3,
            };

            // Test the transient error: Too many Requests/ Request Timeout
            IList <NotificationBatchItemResponse> responses = new List <NotificationBatchItemResponse>();

            responses.Add(new NotificationBatchItemResponse()
            {
                NotificationId = "1", Status = System.Net.HttpStatusCode.TooManyRequests
            });
            responses.Add(new NotificationBatchItemResponse()
            {
                NotificationId = "2", Status = System.Net.HttpStatusCode.RequestTimeout
            });
            responses.Add(new NotificationBatchItemResponse()
            {
                NotificationId = "3", Status = System.Net.HttpStatusCode.Accepted
            });

            Mock <IMSGraphProvider> graphProvider = new Mock <IMSGraphProvider>();

            _ = graphProvider
                .Setup(gp => gp.ProcessEmailRequestBatch(It.IsAny <AuthenticationHeaderValue>(), It.IsAny <GraphBatchRequest>()))
                .Returns(Task.FromResult(responses));

            _ = this.EmailNotificationRepository
                .Setup(repository => repository.GetRepository(StorageType.StorageAccount).GetEmailNotificationItemEntities(It.IsAny <IList <string> >(), It.IsAny <string>()))
                .Returns(Task.FromResult(emailNotificationItemEntities));

            _ = this.TokenHelper
                .Setup(th => th.GetAuthenticationHeaderValueForSelectedAccount(It.IsAny <AccountCredential>()))
                .ReturnsAsync(new AuthenticationHeaderValue(ApplicationConstants.BearerAuthenticationScheme, "Test"));

            this.MSGraphNotificationProvider = new MSGraphNotificationProvider(this.Configuration, this.EmailAccountManager.Object, this.Logger, this.MsGraphSetting, this.TokenHelper.Object, graphProvider.Object, this.EmailManager);

            _ = this.NotificationProviderFactory
                .Setup(provider => provider.GetNotificationProvider(NotificationProviderType.Graph))
                .Returns(this.MSGraphNotificationProvider);

            var emailServiceManager = new EmailServiceManager(this.Configuration, this.EmailNotificationRepository.Object, this.CloudStorageClient.Object, this.Logger, this.NotificationProviderFactory.Object, this.EmailManager);

            Task <IList <NotificationResponse> > result = emailServiceManager.SendEmailNotifications(this.ApplicationName, notificationItems);

            Assert.AreEqual(result.Status.ToString(), "RanToCompletion");
            Assert.AreEqual(result.Result.Count(x => x.Status == NotificationItemStatus.Retrying), 2);
            this.EmailNotificationRepository.Verify(repo => repo.GetRepository(StorageType.StorageAccount).UpdateEmailNotificationItemEntities(It.IsAny <IList <EmailNotificationItemEntity> >()), Times.Once);
            this.CloudStorageClient.Verify(csa => csa.QueueCloudMessages(It.IsAny <CloudQueue>(), It.IsAny <IEnumerable <string> >(), null), Times.Once);
            Assert.Pass();
        }
Пример #6
0
        /// <summary>
        /// Initialization for all Email Manager Tests.
        /// </summary>
        protected void SetupTestBase()
        {
            this.MsGraphProvider             = new Mock <IMSGraphProvider>();
            this.CloudStorageClient          = new Mock <ICloudStorageClient>();
            this.TokenHelper                 = new Mock <ITokenHelper>();
            this.EmailNotificationRepository = new Mock <IRepositoryFactory>();
            this.MsGraphSetting              = Options.Create(new MSGraphSetting()
            {
                EnableBatching = false, SendMailUrl = this.sendEmailUrl, BatchRequestLimit = 4
            });
            this.Logger                      = new Mock <ILogger>().Object;
            this.EncryptionService           = new Mock <IEncryptionService>();
            this.EmailAccountManager         = new Mock <IEmailAccountManager>();
            this.TemplateManager             = new Mock <IMailTemplateManager>();
            this.TemplateMerge               = new Mock <ITemplateMerge>();
            this.NotificationProviderFactory = new Mock <INotificationProviderFactory>();
            this.NotificationRepo            = new Mock <IEmailNotificationRepository>();
            this.NotificationProvider        = new MockNotificationProvider();

            var notificationId = Guid.NewGuid().ToString();
            IList <NotificationBatchItemResponse> responses = new List <NotificationBatchItemResponse>();

            responses.Add(new NotificationBatchItemResponse()
            {
                NotificationId = notificationId, Status = System.Net.HttpStatusCode.Accepted
            });
            var applicationAccounts = new List <ApplicationAccounts>()
            {
                new ApplicationAccounts()
                {
                    ApplicationName = this.ApplicationName,
                    ValidAppIds     = Guid.NewGuid().ToString(),
                    Accounts        = new List <AccountCredential>()
                    {
                        new AccountCredential()
                        {
                            AccountName = "Test", IsEnabled = true, PrimaryPassword = "******",
                        },
                    },
                },
            };

            var retrySetting = new RetrySetting
            {
                MaxRetries          = 10,
                TransientRetryCount = 3,
            };

            IList <EmailNotificationItemEntity> emailNotificationItemEntities = new List <EmailNotificationItemEntity>()
            {
                new EmailNotificationItemEntity()
                {
                    Application    = this.ApplicationName,
                    NotificationId = notificationId,
                    To             = "*****@*****.**",
                    Subject        = "TestEmailSubject",
                    Body           = "CfDJ8KvR5DP4DK5GqV1jviPzBnsv3onVDZ-ztz-AvRl_6nvVNg86jfmKjgySREDPW9xNrwpKALT5BIFNX6VK3wzKsxc51dbkQjPPG9l7436wQktrAMRadumTpGKNKG1lLlP0FA",
                    Id             = notificationId,
                },
            };
            var mailSettings = new List <MailSettings>()
            {
                new MailSettings()
                {
                    ApplicationName = this.ApplicationName,
                    MailOn          = true,
                    SendForReal     = false,
                    ToOverride      = "*****@*****.**",
                    SaveToSent      = true,
                },
            };
            Dictionary <string, string> testConfigValues = new Dictionary <string, string>()
            {
                { "ApplicationAccounts", JsonConvert.SerializeObject(applicationAccounts) },
                { "RetrySetting:MaxRetries", "10" },
                { "RetrySetting:TransientRetryCount", "3" },
                { Constants.StorageType, StorageType.StorageAccount.ToString() },
                { "MailSettings", JsonConvert.SerializeObject(mailSettings) },
                { Constants.NotificationProviderType, NotificationProviderType.Graph.ToString() },
            };

            string mergedTemplate = "Testing Html template";

            MailTemplate template = new MailTemplate()
            {
                TemplateName = "TestTemplate",
                Description  = "Test template",
                Content      = "Testing {{Key}} template",
                TemplateType = "Text",
            };

            this.Configuration = new ConfigurationBuilder()
                                 .AddInMemoryCollection(testConfigValues)
                                 .Build();

            _ = this.TokenHelper
                .Setup(th => th.GetAccessTokenForSelectedAccount(It.IsAny <AccountCredential>()))
                .Returns(Task.FromResult(this.TestToken));

            _ = this.TokenHelper
                .Setup(th => th.GetAuthenticationHeaderFromToken(It.IsAny <string>()))
                .Returns(Task.FromResult(new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", this.TestToken)));

            _ = this.MsGraphProvider
                .Setup(gp => gp.ProcessEmailRequestBatch(It.IsAny <AuthenticationHeaderValue>(), It.IsAny <GraphBatchRequest>()))
                .Returns(Task.FromResult(responses));

            _ = this.MsGraphProvider
                .Setup(gp => gp.SendEmailNotification(It.IsAny <AuthenticationHeaderValue>(), It.IsAny <EmailMessagePayload>(), It.IsAny <string>()))
                .Returns(Task.FromResult(It.IsAny <bool>()));

            _ = this.EmailNotificationRepository
                .Setup(repository => repository.GetRepository(StorageType.StorageAccount).CreateEmailNotificationItemEntities(It.IsAny <IList <EmailNotificationItemEntity> >(), It.IsAny <string>()))
                .Returns(Task.CompletedTask);

            _ = this.EmailNotificationRepository
                .Setup(repository => repository.GetRepository(StorageType.StorageAccount).UpdateEmailNotificationItemEntities(It.IsAny <IList <EmailNotificationItemEntity> >()))
                .Returns(Task.CompletedTask);

            _ = this.EmailNotificationRepository
                .Setup(repository => repository.GetRepository(StorageType.StorageAccount).GetEmailNotificationItemEntities(It.IsAny <IList <string> >(), It.IsAny <string>()))
                .Returns(Task.FromResult(emailNotificationItemEntities));

            _ = this.CloudStorageClient
                .Setup(csa => csa.GetCloudQueue(It.IsAny <string>()))
                .Returns(new CloudQueue(new Uri(this.cloudQueueUri)));

            _ = this.CloudStorageClient
                .Setup(csa => csa.QueueCloudMessages(It.IsAny <CloudQueue>(), It.IsAny <IEnumerable <string> >(), null))
                .Returns(Task.CompletedTask);

            _ = this.EmailAccountManager
                .Setup(ema => ema.FetchAccountToBeUsedForApplication(It.IsAny <string>(), It.IsAny <List <ApplicationAccounts> >()))
                .Returns(applicationAccounts[0].Accounts[0]);

            _ = this.TemplateManager
                .Setup(tmgr => tmgr.GetMailTemplate(It.IsAny <string>(), It.IsAny <string>()))
                .Returns(Task.FromResult(template));

            _ = this.TemplateMerge
                .Setup(tmr => tmr.CreateMailBodyUsingTemplate(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()))
                .Returns(mergedTemplate);
            this.EmailManager = new EmailManager(this.Configuration, this.EmailNotificationRepository.Object, this.Logger, this.TemplateManager.Object, this.TemplateMerge.Object);

            this.MSGraphNotificationProvider = new MSGraphNotificationProvider(
                this.Configuration,
                this.EmailAccountManager.Object,
                this.Logger,
                this.MsGraphSetting,
                Options.Create(retrySetting),
                this.TokenHelper.Object,
                this.MsGraphProvider.Object,
                this.EmailManager);

            _ = this.NotificationProviderFactory
                .Setup(provider => provider.GetNotificationProvider(NotificationProviderType.Graph))
                .Returns(this.MSGraphNotificationProvider);

            this.EmailHandlerManager = new EmailHandlerManager(this.Configuration, this.MsGraphSetting, this.CloudStorageClient.Object, this.Logger, this.EmailManager);
            this.EmailServiceManager = new EmailServiceManager(this.Configuration, this.EmailNotificationRepository.Object, this.CloudStorageClient.Object, this.Logger, this.NotificationProviderFactory.Object, this.EmailManager);
        }