public StorageAccountSetting Update(StorageAccountSetting setting) { if (setting == null) { throw new ArgumentNullException("setting"); } return(SqlQueryExecutor.Execute(() => { String query = string.Format(CultureInfo.InvariantCulture, "UPDATE {1} SET {0} WHERE Id=@Id", UpdateFieldList, TableName); _connectionProvider.CurrentConnection.Execute(query, new { setting.Id, setting.StorageAccountId, setting.SettingName, setting.SettingValue }); String idAndStampQuery = string.Format(CultureInfo.InvariantCulture, "SELECT id AS Id, stamp AS Stamp FROM {0} WHERE id=@Id;", TableName); IdAndStamp idAndStamp = _connectionProvider.CurrentConnection.Query <IdAndStamp>(idAndStampQuery, new { setting.Id }).FirstOrDefault(); if (idAndStamp == null) { throw new MonsterDbException("Account setting update failed"); } setting.Id = idAndStamp.Id; setting.Stamp = idAndStamp.Stamp; return setting; })); }
public StorageAccountSetting Create(StorageAccountSetting setting) { if (setting == null) { throw new ArgumentNullException("setting"); } return(SqlQueryExecutor.Execute(() => { String query = string.Format(CultureInfo.InvariantCulture, "INSERT INTO {1} {0} RETURNING id;", InsertFieldList, TableName); int insertedId = _connectionProvider.CurrentConnection.Query <int>(query, new { setting.StorageAccountId, setting.SettingName, setting.SettingValue }).FirstOrDefault(); if (insertedId <= 0) { throw new MonsterDbException("Account setting insertion failed"); } String idAndStampQuery = string.Format(CultureInfo.InvariantCulture, "SELECT id AS Id, stamp AS Stamp FROM {0} WHERE id=@Id;", TableName); IdAndStamp idAndStamp = _connectionProvider.CurrentConnection.Query <IdAndStamp>(idAndStampQuery, new { Id = insertedId }).FirstOrDefault(); if (idAndStamp == null) { throw new MonsterDbException("Account insertion failed"); } setting.Id = idAndStamp.Id; setting.Stamp = idAndStamp.Stamp; return setting; })); }
/// <summary> /// Initializes a new instance of the <see cref="TableStorageEmailRepository"/> class. /// </summary> /// <param name="storageAccountSetting">primary key of storage account.</param> /// <param name="cloudStorageClient"> cloud storage client for table storage.</param> /// <param name="logger">logger.</param> /// <param name="mailAttachmentRepository">Instnce of the Mail Attachment Repository.</param> public TableStorageEmailRepository(IOptions <StorageAccountSetting> storageAccountSetting, ITableStorageClient cloudStorageClient, ILogger logger, IMailAttachmentRepository mailAttachmentRepository) { this.storageAccountSetting = storageAccountSetting?.Value ?? throw new System.ArgumentNullException(nameof(storageAccountSetting)); this.cloudStorageClient = cloudStorageClient ?? throw new System.ArgumentNullException(nameof(cloudStorageClient)); this.emailHistoryTable = this.cloudStorageClient.GetCloudTable("EmailHistory"); this.meetingHistoryTable = this.cloudStorageClient.GetCloudTable("MeetingHistory"); this.logger = logger ?? throw new System.ArgumentNullException(nameof(logger)); this.mailAttachmentRepository = mailAttachmentRepository; }
/// <summary> /// Initializes a new instance of the <see cref="CloudStorageClient"/> class. /// </summary> /// <param name="storageAccountSetting">Storage Account configuration.</param> /// <param name="logger"><see cref="ILogger"/> instance.</param> public CloudStorageClient(IOptions <StorageAccountSetting> storageAccountSetting, ILogger logger) { this.storageAccountSetting = storageAccountSetting?.Value; this.logger = logger ?? throw new ArgumentNullException(nameof(logger)); this.cloudStorageAccount = CloudStorageAccount.Parse(this.storageAccountSetting.ConnectionString); this.cloudQueueClient = this.cloudStorageAccount.CreateCloudQueueClient(); this.blobContainerClient = new BlobContainerClient(this.storageAccountSetting.ConnectionString, this.storageAccountSetting.BlobContainerName); if (!this.blobContainerClient.Exists()) { this.logger.TraceWarning($"BlobStorageClient - Method: {nameof(CloudStorageClient)} - No container found with name {this.storageAccountSetting.BlobContainerName}."); var response = this.blobContainerClient.CreateIfNotExists(); this.blobContainerClient = new BlobContainerClient(this.storageAccountSetting.ConnectionString, this.storageAccountSetting.BlobContainerName); } }
/// <summary> /// Initializes a new instance of the <see cref="TableStorageEmailRepository"/> class. /// </summary> /// <param name="storageAccountSetting">primary key of storage account.</param> /// <param name="cloudStorageClient"> cloud storage client for table storage.</param> /// <param name="logger">logger.</param> /// <param name="mailAttachmentRepository">Instnce of the Mail Attachment Repository.</param> public TableStorageEmailRepository(IOptions <StorageAccountSetting> storageAccountSetting, ITableStorageClient cloudStorageClient, ILogger logger, IMailAttachmentRepository mailAttachmentRepository) { this.storageAccountSetting = storageAccountSetting?.Value ?? throw new System.ArgumentNullException(nameof(storageAccountSetting)); this.cloudStorageClient = cloudStorageClient ?? throw new System.ArgumentNullException(nameof(cloudStorageClient)); var emailHistoryTableName = storageAccountSetting?.Value?.EmailHistoryTableName; var meetingHistoryTableName = storageAccountSetting?.Value?.MeetingHistoryTableName; if (string.IsNullOrEmpty(emailHistoryTableName)) { throw new ArgumentNullException(nameof(storageAccountSetting), "EmailHistoryTableName property from StorageAccountSetting can't be null/empty. Please provide the value in appsettings.json file."); } if (string.IsNullOrEmpty(meetingHistoryTableName)) { throw new ArgumentNullException(nameof(storageAccountSetting), "MeetingHistoryTableName property from StorageAccountSetting can't be null/empty. Please provide the value in appsettings.json file"); } this.emailHistoryTable = this.cloudStorageClient.GetCloudTable(emailHistoryTableName); this.meetingHistoryTable = this.cloudStorageClient.GetCloudTable(meetingHistoryTableName); this.logger = logger ?? throw new System.ArgumentNullException(nameof(logger)); this.mailAttachmentRepository = mailAttachmentRepository; }
public UpdateResult SaveSettings(IDictionary <string, string> storageAccountSettingsList, int storageAccountId, DateTime storageAccountStamp) { if (storageAccountSettingsList == null) { throw new ArgumentNullException("storageAccountSettingsList"); } if (storageAccountSettingsList.Count <= 0) { return(UpdateResult.Success); } return(SqlQueryExecutor.Execute(() => { return _connectionProvider.DoInTransaction(() => { const string selectAccountWithStampQuery = "SELECT a.id FROM storage_accounts a WHERE a.id = @Id AND a.stamp = @Stamp LIMIT 1;"; int?accountIdCheck = _connectionProvider.CurrentConnection.Query <int?>(selectAccountWithStampQuery, new { Id = storageAccountId, Stamp = storageAccountStamp }).FirstOrDefault(); if (accountIdCheck == null) { const string selectAccountQueryWithoutStamp = "SELECT a.id FROM storage_accounts a WHERE a.id = @Id LIMIT 1;"; accountIdCheck = _connectionProvider.CurrentConnection.Query <int?>(selectAccountQueryWithoutStamp, new { Id = storageAccountId }).FirstOrDefault(); if (accountIdCheck == null) { return UpdateResult.ItemNotExists; } return UpdateResult.Stalled; } foreach (var accountSetting in storageAccountSettingsList) { StorageAccountSetting setting = LoadByName(accountSetting.Key, storageAccountId); if (setting == null) { setting = new StorageAccountSetting { StorageAccountId = storageAccountId, SettingName = accountSetting.Key, SettingValue = accountSetting.Value }; Create(setting); } else { setting.SettingName = accountSetting.Key; setting.SettingValue = accountSetting.Value; Update(setting); } } const string insertQuery = "UPDATE storage_accounts SET stamp = now() WHERE id = @Id;"; _connectionProvider.CurrentConnection.Execute(insertQuery, new { Id = storageAccountId }); return UpdateResult.Success; }); })); }
#pragma warning restore SA1401 // Fields should be private #pragma warning restore SA1201 // Elements should appear in the correct order /// <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, }, }; var storageAccountSettings = new StorageAccountSetting() { NotificationQueueName = "test-queue", }; Dictionary <string, string> testConfigValues = new Dictionary <string, string>() { { "ApplicationAccounts", JsonConvert.SerializeObject(applicationAccounts) }, { "RetrySetting:MaxRetries", "10" }, { "RetrySetting:TransientRetryCount", "3" }, { ConfigConstants.StorageType, StorageType.StorageAccount.ToString() }, { "MailSettings", JsonConvert.SerializeObject(mailSettings) }, { ConfigConstants.StorageAccountConfigSectionKey, JsonConvert.SerializeObject(storageAccountSettings) }, { ConfigConstants.NotificationProviderType, NotificationProviderType.Graph.ToString() }, }; string mergedTemplate = "Testing Html template"; MailTemplate template = new MailTemplate() { TemplateId = "TestTemplate", Description = "Test template", Content = "Testing {{Key}} template", TemplateType = "Text", }; this.response = new ResponseData <string>() { Status = true, Result = "successful", StatusCode = HttpStatusCode.OK, }; 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(ApplicationConstants.BearerAuthenticationScheme, 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(this.response)); _ = 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, 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); }
/// <summary> /// Initializes a new instance of the <see cref="TableStorageClient"/> class. /// </summary> /// <param name="storageAccountSetting">Storage Account configuration.</param> public TableStorageClient(IOptions <StorageAccountSetting> storageAccountSetting) { this.storageAccountSetting = storageAccountSetting?.Value; this.cloudStorageAccount = CloudStorageAccount.Parse(this.storageAccountSetting.ConnectionString); this.cloudTableClient = this.cloudStorageAccount.CreateCloudTableClient(); }