/// <summary> /// Converts <see cref="EmailNotificationItem"/> to a <see cref="EmailNotificationItemEntity"/>. /// </summary> /// <param name="emailNotificationItem">Email Notification Item.</param> /// <param name="applicationName">Application associated to the notification item.</param> /// <returns><see cref="EmailNotificationItemEntity"/>.</returns> public static EmailNotificationItemEntity ToEntity(this EmailNotificationItem emailNotificationItem, string applicationName) { if (emailNotificationItem != null) { return(new EmailNotificationItemEntity() { Application = applicationName, Attachments = emailNotificationItem?.Attachments?.Select(attachment => new NotificationAttachmentEntity { IsInline = attachment.IsInline, FileName = attachment?.FileName, FileBase64 = attachment?.FileBase64 }).ToList(), BCC = emailNotificationItem?.BCC, Body = emailNotificationItem?.Body, CC = emailNotificationItem?.CC, Footer = emailNotificationItem?.Footer, From = emailNotificationItem?.From, Header = emailNotificationItem?.Header, Priority = emailNotificationItem.Priority, ReplyTo = emailNotificationItem?.ReplyTo, SendOnUtcDate = emailNotificationItem.SendOnUtcDate, Sensitivity = emailNotificationItem.Sensitivity, Subject = emailNotificationItem?.Subject, To = emailNotificationItem?.To, TemplateData = emailNotificationItem?.TemplateData, TemplateId = emailNotificationItem?.TemplateId, TrackingId = emailNotificationItem?.TrackingId, }); } return(null); }
/// <summary> /// sends email using template /// </summary> /// <param name="mailTemplate"> template .</param> /// <param name="TemplateData">template data params .</param> private async Task SendEmailTemplateTest(MailTemplate mailTemplate, string TemplateData) { var emailNotificationItems = new EmailNotificationItem[] { new EmailNotificationItem() { To = this.Configuration[FunctionalConstants.ToAddress], Subject = "Email Notification Functional Testing of Template through send endpoint", Priority = NotificationPriority.Low, TemplateId = mailTemplate.TemplateId, TemplateData = TemplateData } }; var stringContent = new StringContent(JsonConvert.SerializeObject(emailNotificationItems), Encoding.UTF8, FunctionalConstants.ContentType); string notificationServiceEndpoint = $"{this.Configuration[FunctionalConstants.NotificationServiceUrl]}/v1/email/send/{this.Configuration[FunctionalConstants.Application]}"; using (HttpClient httpClient = new HttpClient()) { string bearerToken = await this.tokenUtility.GetTokenAsync(); if (bearerToken != null) { httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(FunctionalConstants.Bearer, bearerToken); var response = await httpClient.PostAsync(notificationServiceEndpoint, stringContent).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); Assert.Fail(); } else { var Result = response.Content.ReadAsStringAsync().Result; var notificationResponses = JsonConvert.DeserializeObject <List <NotificationResponse> >(Result); var notificationResponse = notificationResponses.FirstOrDefault(); Assert.IsTrue(notificationResponse.Status == NotificationItemStatus.Sent); EmailMessage emailMessage = await GetEmailNotificationMessage(notificationResponse.NotificationId, httpClient); if (emailMessage != null) { var templateBody = ConvertText(mailTemplate.Content, TemplateData); Assert.IsTrue(emailNotificationItems[0].Subject == emailMessage.Subject); Assert.IsTrue(templateBody == emailMessage.Body.Content); } else { Assert.Fail(); } } } else { Assert.Fail(); } } }
public async Task SendEmailTest() { var emailNotificationItems = new EmailNotificationItem[] { new EmailNotificationItem() { To = Configuration[FunctionalConstants.ToAddress], Subject = "Notification Functional Testing of Email Send Endpoint", Body = "Hello world!" } }; var stringContent = new StringContent(JsonConvert.SerializeObject(emailNotificationItems), Encoding.UTF8, FunctionalConstants.ContentType); string notificationServiceEndpoint = $"{this.Configuration[FunctionalConstants.NotificationServiceUrl]}/v1/email/send/{this.Configuration[FunctionalConstants.Application]}"; using (HttpClient httpClient = new HttpClient()) { string bearerToken = await this.tokenUtility.GetTokenAsync(); if (bearerToken != null) { httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(FunctionalConstants.Bearer, bearerToken); var response = await httpClient.PostAsync(notificationServiceEndpoint, stringContent).ConfigureAwait(false);; if (!response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); Assert.Fail(); } else { var Result = response.Content.ReadAsStringAsync().Result; var notificationResponses = JsonConvert.DeserializeObject <List <NotificationResponse> >(Result); var notificationResponse = notificationResponses.FirstOrDefault(); Assert.IsTrue(notificationResponse.Status == NotificationItemStatus.Sent); } } else { Assert.Fail(); } } }
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(); }
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(); }
public async Task QueueEmailGetNotificationMessageGetNotificationReportTest() { var emailNotificationItems = new EmailNotificationItem[] { new EmailNotificationItem() { To = Configuration[FunctionalConstants.ToAddress], Subject = "Notification Functional Testing of Email Queue Endpoint", Body = "Hello world!" } }; var stringContent = new StringContent(JsonConvert.SerializeObject(emailNotificationItems), Encoding.UTF8, FunctionalConstants.ContentType); string notificationQueueEndpoint = $"{this.Configuration[FunctionalConstants.NotificationHandlerUrl]}/v1/email/queue/{this.Configuration[FunctionalConstants.Application]}"; using (HttpClient httpClient = new HttpClient()) { string bearerToken = await this.tokenUtility.GetTokenAsync(); if (bearerToken != null) { httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(FunctionalConstants.Bearer, bearerToken); var response = await httpClient.PostAsync(notificationQueueEndpoint, stringContent).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); Assert.Fail(); } else { var Result = response.Content.ReadAsStringAsync().Result; var notificationResponses = JsonConvert.DeserializeObject <List <NotificationResponse> >(Result); var notificationResponse = notificationResponses.FirstOrDefault(); Assert.IsTrue(notificationResponse.Status == NotificationItemStatus.Queued); var notificationId = notificationResponse.NotificationId; EmailMessage emailMessage = await GetNotificationMessageTest(notificationId, httpClient); if (emailMessage != null) { Assert.IsTrue(emailNotificationItems[0].Subject == emailMessage.Subject); Assert.IsTrue(emailNotificationItems[0].Body == emailMessage.Body.Content); } else { Assert.Fail(); } int retryCount = int.TryParse(Configuration[FunctionalConstants.RetryCount], out retryCount) ? retryCount : 2; int delayTime = int.TryParse(Configuration[FunctionalConstants.DelayTimeInMilliSeconds], out delayTime) ? delayTime : 5000; for (int i = 0; i < retryCount; i++) { NotificationReportResponse notificationReportResponse = await GetNotificationReportTest(notificationId, httpClient); if (notificationReportResponse != null) { NotificationItemStatus notificationItemStatus = Enum.TryParse <NotificationItemStatus>(notificationReportResponse.Status, out notificationItemStatus) ? notificationItemStatus : NotificationItemStatus.Queued; switch (notificationItemStatus) { case NotificationItemStatus.Failed: case NotificationItemStatus.FakeMail: case NotificationItemStatus.Invalid: { Assert.Fail(); break; } case NotificationItemStatus.Sent: { Assert.Pass(); break; } case NotificationItemStatus.Queued: case NotificationItemStatus.Processing: case NotificationItemStatus.Retrying: { if (i == retryCount - 1) { Assert.Fail(); break; } await Task.Delay(delayTime); continue; } } } else { Assert.Fail(); } } } } else { Assert.Fail(); } } }
public async Task QueueEmailAttachmentGetNotificationTest() { var emailNotificationItems = new EmailNotificationItem[] { new EmailNotificationItem() { To = Configuration[FunctionalConstants.ToAddress], Subject = "Notification Functional Testing of Email Queue Endpoint with attachments", Body = "Hello world!", Attachments = new List <NotificationAttachment>() { new NotificationAttachment() { FileBase64 = "VEhpcyBpcyBhIHRlc3QgYXR0YWNobWVudCBmaWxlLg==", FileName = "Test.txt", IsInline = false, }, }, } }; var stringContent = new StringContent(JsonConvert.SerializeObject(emailNotificationItems), Encoding.UTF8, FunctionalConstants.ContentType); string notificationQueueEndpoint = $"{this.Configuration[FunctionalConstants.NotificationHandlerUrl]}/v1/email/queue/{this.Configuration[FunctionalConstants.Application]}"; using (HttpClient httpClient = new HttpClient()) { string bearerToken = await this.tokenUtility.GetTokenAsync(); if (bearerToken != null) { httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(FunctionalConstants.Bearer, bearerToken); var response = await httpClient.PostAsync(notificationQueueEndpoint, stringContent).ConfigureAwait(false);; if (!response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); Assert.Fail(); } else { var Result = response.Content.ReadAsStringAsync().Result; var notificationResponses = JsonConvert.DeserializeObject <List <NotificationResponse> >(Result); var notificationResponse = notificationResponses.FirstOrDefault(); Assert.IsTrue(notificationResponse.Status == NotificationItemStatus.Queued); var notificationId = notificationResponse.NotificationId; EmailMessage emailMessage = await GetNotificationMessageTest(notificationId, httpClient); if (emailMessage != null) { Assert.IsTrue(emailNotificationItems[0].Subject == emailMessage.Subject); Assert.IsTrue(emailNotificationItems[0].Body == emailMessage.Body.Content); Assert.IsTrue(emailNotificationItems[0].Attachments.FirstOrDefault().FileName == emailMessage.Attachments.FirstOrDefault().Name); Assert.IsTrue(emailNotificationItems[0].Attachments.FirstOrDefault().FileBase64 == emailMessage.Attachments.FirstOrDefault().ContentBytes); } else { Assert.Fail(); } } } else { Assert.Fail(); } } }