diff --git a/MessagingService.BusinessLogic/Services/EmailServices/Smtp2Go/Smtp2GoProxy.cs b/MessagingService.BusinessLogic/Services/EmailServices/Smtp2Go/Smtp2GoProxy.cs index 44c778c..efb3730 100644 --- a/MessagingService.BusinessLogic/Services/EmailServices/Smtp2Go/Smtp2GoProxy.cs +++ b/MessagingService.BusinessLogic/Services/EmailServices/Smtp2Go/Smtp2GoProxy.cs @@ -1,18 +1,19 @@ namespace MessagingService.BusinessLogic.Services.EmailServices.Smtp2Go { + using Models; + using Newtonsoft.Json; + using Service.Services.Email.Smtp2Go; + using Shared.General; + using Shared.Logger; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Net.Http; + using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; - using Models; - using Newtonsoft.Json; - using Service.Services.Email.Smtp2Go; - using Shared.General; - using Shared.Logger; /// /// @@ -32,10 +33,6 @@ public class Smtp2GoProxy : IEmailServiceProxy #region Constructors - /// - /// Initializes a new instance of the class. - /// - /// The HTTP client. public Smtp2GoProxy(HttpClient httpClient) { this.HttpClient = httpClient; @@ -45,18 +42,6 @@ public Smtp2GoProxy(HttpClient httpClient) #region Methods - /// - /// Sends the email. - /// - /// The message identifier. - /// From address. - /// To addresses. - /// The subject. - /// The body. - /// if set to true [is HTML]. - /// The attachments. - /// The cancellation token. - /// public async Task SendEmail(Guid messageId, String fromAddress, List toAddresses, @@ -64,12 +49,11 @@ public async Task SendEmail(Guid messageId, String body, Boolean isHtml, List attachments, - CancellationToken cancellationToken) - { + CancellationToken cancellationToken) { EmailServiceProxyResponse response = null; // Translate the request message - Smtp2GoSendEmailRequest apiRequest = new Smtp2GoSendEmailRequest + Smtp2GoSendEmailRequest apiRequest = new() { ApiKey = ConfigurationReader.GetValue("SMTP2GoAPIKey"), HTMLBody = isHtml ? body : string.Empty, @@ -100,7 +84,7 @@ public async Task SendEmail(Guid messageId, Logger.LogDebug($"Request Message Sent to Email Provider [SMTP2Go] {requestSerialised}"); - StringContent content = new StringContent(requestSerialised, Encoding.UTF8, "application/json"); + StringContent content = new(requestSerialised, Encoding.UTF8, "application/json"); String requestUri = $"{ConfigurationReader.GetValue("SMTP2GoBaseAddress")}email/send"; HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); @@ -108,11 +92,9 @@ public async Task SendEmail(Guid messageId, HttpResponseMessage httpResponse = await this.HttpClient.SendAsync(requestMessage, cancellationToken); - Smtp2GoSendEmailResponse apiResponse = new Smtp2GoSendEmailResponse(){ - Data = new Smtp2GoSendEmailResponseData() - }; + Smtp2GoSendEmailResponse apiResponse = new() { Data = new Smtp2GoSendEmailResponseData() }; if (httpResponse.IsSuccessStatusCode){ - apiResponse = JsonConvert.DeserializeObject(await httpResponse.Content.ReadAsStringAsync()); + apiResponse = JsonConvert.DeserializeObject(await httpResponse.Content.ReadAsStringAsync(cancellationToken)); } else{ apiResponse = new Smtp2GoSendEmailResponse(); @@ -134,12 +116,7 @@ public async Task SendEmail(Guid messageId, }; return response; } - - /// - /// Converts the type of the file. - /// - /// Type of the email attachment file. - /// + private String ConvertFileType(FileType emailAttachmentFileType) { switch(emailAttachmentFileType) @@ -151,14 +128,6 @@ private String ConvertFileType(FileType emailAttachmentFileType) } } - /// - /// Gets the message status. - /// - /// The provider reference. - /// The start date. - /// The end date. - /// The cancellation token. - /// public async Task GetMessageStatus(String providerReference, DateTime startDate, DateTime endDate, @@ -208,11 +177,6 @@ public async Task GetMessageStatus(String providerReferen return response; } - /// - /// Translates the message status. - /// - /// The status. - /// private MessageStatus TranslateMessageStatus(String status) { MessageStatus result; diff --git a/MessagingService.BusinessLogic/Services/MessagingDomainService.cs b/MessagingService.BusinessLogic/Services/MessagingDomainService.cs index 55e3813..7688474 100644 --- a/MessagingService.BusinessLogic/Services/MessagingDomainService.cs +++ b/MessagingService.BusinessLogic/Services/MessagingDomainService.cs @@ -120,30 +120,34 @@ public async Task> SendEmailMessage(Guid connectionIdentifier, Boolean isHtml, List attachments, CancellationToken cancellationToken) { - Result result = await ApplyEmailUpdates(async (EmailAggregate emailAggregate) => { + Result result = await ApplyEmailUpdates(async (EmailAggregate emailAggregate) => + { // Check if this message has been sent before - if (emailAggregate.GetMessageStatus() != EmailMessageAggregate.MessageStatus.NotSet) { + if (emailAggregate.GetMessageStatus() != EmailMessageAggregate.MessageStatus.NotSet) + { return Result.Success(); } // send message to provider (record event) - emailAggregate.SendRequestToProvider(fromAddress, toAddresses, subject, body, isHtml, attachments); + emailAggregate.SendRequestToProvider(fromAddress, toAddresses, subject, body, isHtml, attachments); // Make call to Email provider here EmailServiceProxyResponse emailResponse = await this.EmailServiceProxy.SendEmail(messageId, fromAddress, toAddresses, subject, body, isHtml, attachments, cancellationToken); - if (emailResponse.ApiCallSuccessful) { + if (emailResponse.ApiCallSuccessful) + { // response message from provider (record event) emailAggregate.ReceiveResponseFromProvider(emailResponse.RequestIdentifier, emailResponse.EmailIdentifier); } - else { + else + { emailAggregate.ReceiveBadResponseFromProvider(emailResponse.Error, emailResponse.ErrorCode); } return Result.Success(); - }, messageId, cancellationToken,false); + }, messageId, cancellationToken, false); if (result.IsFailed) return result; diff --git a/MessagingService.BusinessLogic/Services/SMSServices/TheSMSWorks/TheSmsWorksProxy.cs b/MessagingService.BusinessLogic/Services/SMSServices/TheSMSWorks/TheSmsWorksProxy.cs index e30db77..325f234 100644 --- a/MessagingService.BusinessLogic/Services/SMSServices/TheSMSWorks/TheSmsWorksProxy.cs +++ b/MessagingService.BusinessLogic/Services/SMSServices/TheSMSWorks/TheSmsWorksProxy.cs @@ -18,6 +18,12 @@ namespace MessagingService.BusinessLogic.Services.SMSServices.TheSMSWorks [ExcludeFromCodeCoverage] public class TheSmsWorksProxy : ISMSServiceProxy { + private readonly HttpClient HttpClient; + + public TheSmsWorksProxy(HttpClient httpClient) { + this.HttpClient = httpClient; + } + /// /// Sends the SMS. /// @@ -31,130 +37,86 @@ public async Task SendSMS(Guid messageId, String sender, String destination, String message, - CancellationToken cancellationToken) - { + CancellationToken cancellationToken) { SMSServiceProxyResponse response = null; - using(HttpClient client = new HttpClient()) - { - // Create the Auth Request - TheSmsWorksTokenRequest apiTokenRequest = new TheSmsWorksTokenRequest - { - CustomerId = ConfigurationReader.GetValue("TheSMSWorksCustomerId"), - Key = ConfigurationReader.GetValue("TheSMSWorksKey"), - Secret = ConfigurationReader.GetValue("TheSMSWorksSecret") - }; - - String apiTokenRequestSerialised = JsonConvert.SerializeObject(apiTokenRequest).ToLower(); - StringContent content = new StringContent(apiTokenRequestSerialised, Encoding.UTF8, "application/json"); - - // First do the authentication - HttpResponseMessage apiTokenHttpResponse = await client.PostAsync($"{ConfigurationReader.GetValue("TheSMSWorksBaseAddress")}auth/token", content, cancellationToken); - - if (apiTokenHttpResponse.IsSuccessStatusCode) - { - TheSmsWorksTokenResponse apiTokenResponse = - JsonConvert.DeserializeObject(await apiTokenHttpResponse.Content.ReadAsStringAsync()); - - // Now do the actual send - TheSmsWorksSendSMSRequest apiSendSmsRequest = new TheSmsWorksSendSMSRequest - { - Content = message, - Sender = sender, - Destination = destination, - Schedule = string.Empty, - Tag = messageId.ToString(), - Ttl = 0 - }; - - String apiSendSMSMessageRequestSerialised = JsonConvert.SerializeObject(apiSendSmsRequest).ToLower(); - content = new StringContent(apiSendSMSMessageRequestSerialised, Encoding.UTF8, "application/json"); - - client.DefaultRequestHeaders.Add("Authorization", apiTokenResponse.Token); - HttpResponseMessage apiSendSMSMessageHttpResponse = - await client.PostAsync($"{ConfigurationReader.GetValue("TheSMSWorksBaseAddress")}message/send", content, cancellationToken); - - if (apiSendSMSMessageHttpResponse.IsSuccessStatusCode) - { - // Message has been sent - TheSmsWorksSendSMSResponse apiTheSmsWorksSendSmsResponse = - JsonConvert.DeserializeObject(await apiSendSMSMessageHttpResponse.Content.ReadAsStringAsync()); - - response = new SMSServiceProxyResponse - { - ApiCallSuccessful = true, - SMSIdentifier = apiTheSmsWorksSendSmsResponse.MessageId, - }; - } - else - { - response = await HandleAPIError(apiSendSMSMessageHttpResponse); - } + // Create the Auth Request + TheSmsWorksTokenRequest apiTokenRequest = new TheSmsWorksTokenRequest { CustomerId = ConfigurationReader.GetValue("TheSMSWorksCustomerId"), Key = ConfigurationReader.GetValue("TheSMSWorksKey"), Secret = ConfigurationReader.GetValue("TheSMSWorksSecret") }; + + String apiTokenRequestSerialised = JsonConvert.SerializeObject(apiTokenRequest).ToLower(); + StringContent content = new StringContent(apiTokenRequestSerialised, Encoding.UTF8, "application/json"); + + // First do the authentication + HttpResponseMessage apiTokenHttpResponse = await this.HttpClient.PostAsync($"{ConfigurationReader.GetValue("TheSMSWorksBaseAddress")}auth/token", content, cancellationToken); + + if (apiTokenHttpResponse.IsSuccessStatusCode) { + TheSmsWorksTokenResponse apiTokenResponse = JsonConvert.DeserializeObject(await apiTokenHttpResponse.Content.ReadAsStringAsync()); + + // Now do the actual send + TheSmsWorksSendSMSRequest apiSendSmsRequest = new TheSmsWorksSendSMSRequest { + Content = message, + Sender = sender, + Destination = destination, + Schedule = string.Empty, + Tag = messageId.ToString(), + Ttl = 0 + }; + + String apiSendSMSMessageRequestSerialised = JsonConvert.SerializeObject(apiSendSmsRequest).ToLower(); + content = new StringContent(apiSendSMSMessageRequestSerialised, Encoding.UTF8, "application/json"); + + this.HttpClient.DefaultRequestHeaders.Add("Authorization", apiTokenResponse.Token); + HttpResponseMessage apiSendSMSMessageHttpResponse = await this.HttpClient.PostAsync($"{ConfigurationReader.GetValue("TheSMSWorksBaseAddress")}message/send", content, cancellationToken); + + if (apiSendSMSMessageHttpResponse.IsSuccessStatusCode) { + // Message has been sent + TheSmsWorksSendSMSResponse apiTheSmsWorksSendSmsResponse = JsonConvert.DeserializeObject(await apiSendSMSMessageHttpResponse.Content.ReadAsStringAsync()); + + response = new SMSServiceProxyResponse { ApiCallSuccessful = true, SMSIdentifier = apiTheSmsWorksSendSmsResponse.MessageId, }; } - else - { - response = await HandleAPIError(apiTokenHttpResponse); + else { + response = await HandleAPIError(apiSendSMSMessageHttpResponse); } - + } + else { + response = await HandleAPIError(apiTokenHttpResponse); } return response; } public async Task GetMessageStatus(String providerReference, - CancellationToken cancellationToken) - { + CancellationToken cancellationToken) { MessageStatusResponse response = new MessageStatusResponse(); - using (HttpClient client = new HttpClient()) - { - // Create the Auth Request - TheSmsWorksTokenRequest apiTokenRequest = new TheSmsWorksTokenRequest - { - CustomerId = ConfigurationReader.GetValue("TheSMSWorksCustomerId"), - Key = ConfigurationReader.GetValue("TheSMSWorksKey"), - Secret = ConfigurationReader.GetValue("TheSMSWorksSecret") - }; + // Create the Auth Request + TheSmsWorksTokenRequest apiTokenRequest = new TheSmsWorksTokenRequest { CustomerId = ConfigurationReader.GetValue("TheSMSWorksCustomerId"), Key = ConfigurationReader.GetValue("TheSMSWorksKey"), Secret = ConfigurationReader.GetValue("TheSMSWorksSecret") }; - String apiTokenRequestSerialised = JsonConvert.SerializeObject(apiTokenRequest).ToLower(); - StringContent content = new StringContent(apiTokenRequestSerialised, Encoding.UTF8, "application/json"); - - // First do the authentication - HttpResponseMessage apiTokenHttpResponse = await client.PostAsync($"{ConfigurationReader.GetValue("TheSMSWorksBaseAddress")}auth/token", content, cancellationToken); - - if (apiTokenHttpResponse.IsSuccessStatusCode) - { - TheSmsWorksTokenResponse apiTokenResponse = - JsonConvert.DeserializeObject(await apiTokenHttpResponse.Content.ReadAsStringAsync()); - - client.DefaultRequestHeaders.Add("Authorization", apiTokenResponse.Token); - HttpResponseMessage apiGetSMSMessageHttpResponse = - await client.GetAsync($"{ConfigurationReader.GetValue("TheSMSWorksBaseAddress")}messages/{providerReference}", cancellationToken); - - if (apiGetSMSMessageHttpResponse.IsSuccessStatusCode) - { - // Message has been sent - TheSMSWorksGetMessageResponse apiSmsWorksGetMessageResponse = - JsonConvert.DeserializeObject(await apiGetSMSMessageHttpResponse.Content.ReadAsStringAsync()); - - response = new MessageStatusResponse - { - ApiStatusCode = apiGetSMSMessageHttpResponse.StatusCode, - MessageStatus = this.TranslateMessageStatus(apiSmsWorksGetMessageResponse.Status), - ProviderStatusDescription = apiSmsWorksGetMessageResponse.Status, - Timestamp = DateTime.Parse(apiSmsWorksGetMessageResponse.Modified) - }; - } - else - { - throw new NotFoundException($"Error getting message Id [{providerReference}]"); - } + String apiTokenRequestSerialised = JsonConvert.SerializeObject(apiTokenRequest).ToLower(); + StringContent content = new StringContent(apiTokenRequestSerialised, Encoding.UTF8, "application/json"); + + // First do the authentication + HttpResponseMessage apiTokenHttpResponse = await this.HttpClient.PostAsync($"{ConfigurationReader.GetValue("TheSMSWorksBaseAddress")}auth/token", content, cancellationToken); + + if (apiTokenHttpResponse.IsSuccessStatusCode) { + TheSmsWorksTokenResponse apiTokenResponse = JsonConvert.DeserializeObject(await apiTokenHttpResponse.Content.ReadAsStringAsync()); + + this.HttpClient.DefaultRequestHeaders.Add("Authorization", apiTokenResponse.Token); + HttpResponseMessage apiGetSMSMessageHttpResponse = await this.HttpClient.GetAsync($"{ConfigurationReader.GetValue("TheSMSWorksBaseAddress")}messages/{providerReference}", cancellationToken); + + if (apiGetSMSMessageHttpResponse.IsSuccessStatusCode) { + // Message has been sent + TheSMSWorksGetMessageResponse apiSmsWorksGetMessageResponse = JsonConvert.DeserializeObject(await apiGetSMSMessageHttpResponse.Content.ReadAsStringAsync()); + + response = new MessageStatusResponse { ApiStatusCode = apiGetSMSMessageHttpResponse.StatusCode, MessageStatus = this.TranslateMessageStatus(apiSmsWorksGetMessageResponse.Status), ProviderStatusDescription = apiSmsWorksGetMessageResponse.Status, Timestamp = DateTime.Parse(apiSmsWorksGetMessageResponse.Modified) }; } - else - { - throw new Exception("Authentication Error"); + else { + throw new NotFoundException($"Error getting message Id [{providerReference}]"); } } + else { + throw new Exception("Authentication Error"); + } return response; } diff --git a/MessagingService.Client/MessagingService.Client.csproj b/MessagingService.Client/MessagingService.Client.csproj index d95a596..dad1623 100644 --- a/MessagingService.Client/MessagingService.Client.csproj +++ b/MessagingService.Client/MessagingService.Client.csproj @@ -6,9 +6,9 @@ - + - + diff --git a/MessagingService.EmailAggregate.Tests/MessagingService.EmailAggregate.Tests.csproj b/MessagingService.EmailAggregate.Tests/MessagingService.EmailAggregate.Tests.csproj index cc2716b..cd40ac7 100644 --- a/MessagingService.EmailAggregate.Tests/MessagingService.EmailAggregate.Tests.csproj +++ b/MessagingService.EmailAggregate.Tests/MessagingService.EmailAggregate.Tests.csproj @@ -8,7 +8,7 @@ - + diff --git a/MessagingService.EmailMessage.DomainEvents/MessagingService.EmailMessage.DomainEvents.csproj b/MessagingService.EmailMessage.DomainEvents/MessagingService.EmailMessage.DomainEvents.csproj index 858edfb..0fa0080 100644 --- a/MessagingService.EmailMessage.DomainEvents/MessagingService.EmailMessage.DomainEvents.csproj +++ b/MessagingService.EmailMessage.DomainEvents/MessagingService.EmailMessage.DomainEvents.csproj @@ -6,8 +6,8 @@ - - + + diff --git a/MessagingService.EmailMessageAggregate/MessagingService.EmailMessageAggregate.csproj b/MessagingService.EmailMessageAggregate/MessagingService.EmailMessageAggregate.csproj index 0842698..cd2a3fa 100644 --- a/MessagingService.EmailMessageAggregate/MessagingService.EmailMessageAggregate.csproj +++ b/MessagingService.EmailMessageAggregate/MessagingService.EmailMessageAggregate.csproj @@ -6,8 +6,8 @@ - - + + diff --git a/MessagingService.IntegrationTesting.Helpers/MessagingService.IntegrationTesting.Helpers.csproj b/MessagingService.IntegrationTesting.Helpers/MessagingService.IntegrationTesting.Helpers.csproj index a2f6cbb..006e04a 100644 --- a/MessagingService.IntegrationTesting.Helpers/MessagingService.IntegrationTesting.Helpers.csproj +++ b/MessagingService.IntegrationTesting.Helpers/MessagingService.IntegrationTesting.Helpers.csproj @@ -7,7 +7,7 @@ - + diff --git a/MessagingService.IntegrationTests/Common/DockerHelper.cs b/MessagingService.IntegrationTests/Common/DockerHelper.cs index 287f26c..9cf6c40 100644 --- a/MessagingService.IntegrationTests/Common/DockerHelper.cs +++ b/MessagingService.IntegrationTests/Common/DockerHelper.cs @@ -1,10 +1,7 @@ -namespace MessagingService.IntegrationTests.Common +using ClientProxyBase; + +namespace MessagingService.IntegrationTests.Common { - using System; - using System.Collections.Generic; - using System.Linq; - using System.Net.Http; - using System.Threading.Tasks; using Client; using Ductus.FluentDocker.Builders; using Ductus.FluentDocker.Common; @@ -14,7 +11,13 @@ using global::Shared.IntegrationTesting; using global::Shared.Logger; using IntegrationTesting.Helpers; + using Microsoft.AspNetCore.Http; using SecurityService.Client; + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net.Http; + using System.Threading.Tasks; /// /// @@ -76,22 +79,40 @@ public override async Task StartContainersForScenarioRun(String scenarioName, Do // Setup the base address resolvers String SecurityServiceBaseAddressResolver(String api) => $"https://127.0.0.1:{this.SecurityServicePort}"; String MessagingServiceBaseAddressResolver(String api) => $"http://127.0.0.1:{this.MessagingServicePort}"; - - HttpClientHandler clientHandler = new HttpClientHandler - { - ServerCertificateCustomValidationCallback = (message, - certificate2, - arg3, - arg4) => - { - return true; - } - - }; - HttpClient httpClient = new HttpClient(clientHandler); + + HttpClient httpClient = CreateHttpClient(); + this.SecurityServiceClient = new SecurityServiceClient(SecurityServiceBaseAddressResolver, httpClient); this.MessagingServiceClient = new MessagingServiceClient(MessagingServiceBaseAddressResolver, httpClient); } #endregion + + private HttpClient CreateHttpClient() { + // Set up test HttpContext + DefaultHttpContext context = new DefaultHttpContext(); + context.TraceIdentifier = this.TestId.ToString(); + + HttpContextAccessor httpContextAccessor = new HttpContextAccessor + { + HttpContext = context + }; + + // Configure inner-most handler with SSL bypass + HttpClientHandler clientHandler = new HttpClientHandler + { + ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true + }; + + // Wrap with CorrelationIdHandler + CorrelationIdHandler correlationHandler = new CorrelationIdHandler(httpContextAccessor) + { + InnerHandler = clientHandler + }; + + // Create HttpClient + HttpClient client = new HttpClient(correlationHandler); + + return client; + } } } diff --git a/MessagingService.IntegrationTests/MessagingService.IntegrationTests.csproj b/MessagingService.IntegrationTests/MessagingService.IntegrationTests.csproj index c43aa3e..132ffda 100644 --- a/MessagingService.IntegrationTests/MessagingService.IntegrationTests.csproj +++ b/MessagingService.IntegrationTests/MessagingService.IntegrationTests.csproj @@ -6,7 +6,7 @@ - + @@ -14,9 +14,9 @@ - - - + + + all diff --git a/MessagingService.SMSMessage.DomainEvents/MessagingService.SMSMessage.DomainEvents.csproj b/MessagingService.SMSMessage.DomainEvents/MessagingService.SMSMessage.DomainEvents.csproj index ba8f328..2efc869 100644 --- a/MessagingService.SMSMessage.DomainEvents/MessagingService.SMSMessage.DomainEvents.csproj +++ b/MessagingService.SMSMessage.DomainEvents/MessagingService.SMSMessage.DomainEvents.csproj @@ -6,7 +6,7 @@ - + diff --git a/MessagingService.SMSMessageAggregate/MessagingService.SMSMessageAggregate.csproj b/MessagingService.SMSMessageAggregate/MessagingService.SMSMessageAggregate.csproj index 863ef39..fa13261 100644 --- a/MessagingService.SMSMessageAggregate/MessagingService.SMSMessageAggregate.csproj +++ b/MessagingService.SMSMessageAggregate/MessagingService.SMSMessageAggregate.csproj @@ -6,7 +6,7 @@ - + diff --git a/MessagingService.Tests/MessagingService.Tests.csproj b/MessagingService.Tests/MessagingService.Tests.csproj index f7c43eb..3607cf2 100644 --- a/MessagingService.Tests/MessagingService.Tests.csproj +++ b/MessagingService.Tests/MessagingService.Tests.csproj @@ -7,8 +7,8 @@ - - + + diff --git a/MessagingService/Bootstrapper/MessagingProxyRegistry.cs b/MessagingService/Bootstrapper/MessagingProxyRegistry.cs index 2a3d8de..ac431c2 100644 --- a/MessagingService/Bootstrapper/MessagingProxyRegistry.cs +++ b/MessagingService/Bootstrapper/MessagingProxyRegistry.cs @@ -1,43 +1,32 @@ namespace MessagingService.Bootstrapper; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Net.Http; using BusinessLogic.Services.EmailServices; using BusinessLogic.Services.EmailServices.Smtp2Go; using BusinessLogic.Services.SMSServices; using BusinessLogic.Services.SMSServices.TheSMSWorks; +using ClientProxyBase; using Lamar; using Microsoft.Extensions.DependencyInjection; using Service.Services.Email.IntegrationTest; using Service.Services.SMSServices.IntegrationTest; using Shared.General; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; [ExcludeFromCodeCoverage] public class MessagingProxyRegistry : ServiceRegistry { public MessagingProxyRegistry() { - SocketsHttpHandler httpMessageHandler = new SocketsHttpHandler - { - SslOptions = - { - RemoteCertificateValidationCallback = (sender, - certificate, - chain, - errors) => true, - } - }; - HttpClient httpClient = new HttpClient(httpMessageHandler); - this.AddSingleton(httpClient); - + this.AddHttpContextAccessor(); + this.RegisterEmailProxy(); this.RegisterSMSProxy(); } - /// - /// Registers the email proxy. - /// - /// The services. + private void RegisterEmailProxy() { // read the config setting @@ -45,7 +34,7 @@ private void RegisterEmailProxy() if (emailProxy == "Smtp2Go") { - this.AddSingleton(); + this.RegisterHttpClient(); } else { @@ -60,7 +49,7 @@ private void RegisterSMSProxy() if (emailProxy == "TheSMSWorks") { - this.AddSingleton(); + this.RegisterHttpClient(); } else { diff --git a/MessagingService/Bootstrapper/RepositoryRegistry.cs b/MessagingService/Bootstrapper/RepositoryRegistry.cs index 3937d3e..618c770 100644 --- a/MessagingService/Bootstrapper/RepositoryRegistry.cs +++ b/MessagingService/Bootstrapper/RepositoryRegistry.cs @@ -24,30 +24,14 @@ public class RepositoryRegistry: ServiceRegistry { public RepositoryRegistry() { - Boolean useConnectionStringConfig = Boolean.Parse(ConfigurationReader.GetValue("AppSettings", "UseConnectionStringConfig")); - - if (useConnectionStringConfig) - { - String connectionStringConfigurationConnString = ConfigurationReader.GetConnectionString("ConnectionStringConfiguration"); - this.AddSingleton(); - this.AddTransient(c => - { - return new ConnectionStringConfigurationContext(connectionStringConfigurationConnString); - }); - - // TODO: Read this from a the database and set - } - else - { - String connectionString = Startup.Configuration.GetValue("EventStoreSettings:ConnectionString"); - - this.AddEventStoreProjectionManagementClient(connectionString); - this.AddEventStorePersistentSubscriptionsClient(connectionString); - - this.AddEventStoreClient(connectionString); - - this.AddSingleton(); - } + String connectionString = Startup.Configuration.GetValue("EventStoreSettings:ConnectionString"); + + this.AddEventStoreProjectionManagementClient(connectionString); + this.AddEventStorePersistentSubscriptionsClient(connectionString); + + this.AddEventStoreClient(connectionString); + + this.AddSingleton(); this.AddTransient(); diff --git a/MessagingService/Controllers/EmailController.cs b/MessagingService/Controllers/EmailController.cs index 763dbbb..1ae7fd1 100644 --- a/MessagingService/Controllers/EmailController.cs +++ b/MessagingService/Controllers/EmailController.cs @@ -28,7 +28,7 @@ namespace MessagingService.Controllers [ExcludeFromCodeCoverage] [Route(EmailController.ControllerRoute)] [ApiController] - [Authorize] + //[Authorize] public class EmailController : ControllerBase { #region Fields diff --git a/MessagingService/MessagingService.csproj b/MessagingService/MessagingService.csproj index b64c184..56eefe9 100644 --- a/MessagingService/MessagingService.csproj +++ b/MessagingService/MessagingService.csproj @@ -18,11 +18,13 @@ - + + - + + diff --git a/MessagingService/Program.cs b/MessagingService/Program.cs index 9d63297..bd5248c 100644 --- a/MessagingService/Program.cs +++ b/MessagingService/Program.cs @@ -1,21 +1,25 @@ -using System; -using System.IO; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; +using System; +using System.IO; +using Shared.Logger; +using Shared.Middleware; namespace MessagingService { - using System.Diagnostics.CodeAnalysis; using Lamar.Microsoft.DependencyInjection; + using NLog; + using System.Diagnostics.CodeAnalysis; [ExcludeFromCodeCoverage] public class Program { public static void Main(string[] args) { - Program.CreateHostBuilder(args).Build().Run(); + Program.CreateHostBuilder(args).Build() .Run(); } public static IHostBuilder CreateHostBuilder(string[] args) @@ -28,12 +32,27 @@ public static IHostBuilder CreateHostBuilder(string[] args) .AddJsonFile("hosting.development.json", optional: true) .AddEnvironmentVariables().Build(); + String contentRoot = Directory.GetCurrentDirectory(); + String nlogConfigPath = Path.Combine(contentRoot, "nlog.config"); + + LogManager.Setup(b => + { + b.SetupLogFactory(setup => + { + setup.AddCallSiteHiddenAssembly(typeof(NlogLogger).Assembly); + setup.AddCallSiteHiddenAssembly(typeof(Shared.Logger.Logger).Assembly); + setup.AddCallSiteHiddenAssembly(typeof(TenantMiddleware).Assembly); + }); + b.LoadConfigurationFromFile(nlogConfigPath); + }); + IHostBuilder hostBuilder = Host.CreateDefaultBuilder(args); hostBuilder.UseWindowsService(); hostBuilder.UseLamar(); hostBuilder.ConfigureLogging(logging => { logging.AddConsole(); + logging.AddNLog(); }).ConfigureWebHostDefaults(webBuilder => { @@ -41,6 +60,8 @@ public static IHostBuilder CreateHostBuilder(string[] args) webBuilder.UseConfiguration(config); webBuilder.UseKestrel(); }); + + return hostBuilder; } } diff --git a/MessagingService/Startup.cs b/MessagingService/Startup.cs index c5b6b0c..b97e1a1 100644 --- a/MessagingService/Startup.cs +++ b/MessagingService/Startup.cs @@ -1,18 +1,14 @@ -using System; -using System.Collections.Generic; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; namespace MessagingService { - using System.Diagnostics; - using System.Diagnostics.CodeAnalysis; - using System.IO; - using System.Threading; using Bootstrapper; using Common; using EmailMessage.DomainEvents; @@ -20,6 +16,7 @@ namespace MessagingService using HealthChecks.UI.Client; using Lamar; using Microsoft.AspNetCore.Diagnostics.HealthChecks; + using NLog; using NLog.Extensions.Logging; using Shared.EventStore.Aggregate; using Shared.EventStore.EventHandling; @@ -27,7 +24,12 @@ namespace MessagingService using Shared.Extensions; using Shared.General; using Shared.Logger; + using Shared.Middleware; using SMSMessage.DomainEvents; + using System.Diagnostics; + using System.Diagnostics.CodeAnalysis; + using System.IO; + using System.Threading; [ExcludeFromCodeCoverage] public class Startup @@ -68,34 +70,23 @@ public void ConfigureContainer(ServiceRegistry services) // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) { - String nlogConfigFilename = "nlog.config"; - if (env.IsDevelopment()) { - var developmentNlogConfigFilename = "nlog.development.config"; - if (File.Exists(Path.Combine(env.ContentRootPath, developmentNlogConfigFilename))) - { - nlogConfigFilename = developmentNlogConfigFilename; - } - app.UseDeveloperExceptionPage(); } - - loggerFactory.ConfigureNLog(Path.Combine(env.ContentRootPath, nlogConfigFilename)); - loggerFactory.AddNLog(); - + Microsoft.Extensions.Logging.ILogger logger = loggerFactory.CreateLogger("MessagingService"); - Logger.Initialise(logger); - Startup.Configuration.LogConfiguration(Logger.LogWarning); - + Shared.Logger.Logger.Initialise(logger); + Startup.Configuration.LogConfiguration(Shared.Logger.Logger.LogWarning); + foreach (KeyValuePair type in TypeMap.Map) { - Logger.LogInformation($"Type name {type.Value} mapped to {type.Key.Name}"); + Shared.Logger.Logger.LogInformation($"Type name {type.Value} mapped to {type.Key.Name}"); } ConfigurationReader.Initialise(Startup.Configuration); - + app.UseMiddleware(); app.AddRequestLogging(); app.AddResponseLogging(); app.AddExceptionHandler(); @@ -109,15 +100,15 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerF { endpoints.MapControllers(); endpoints.MapHealthChecks("health", new HealthCheckOptions() - { - Predicate = _ => true, - ResponseWriter = Shared.HealthChecks.HealthCheckMiddleware.WriteResponse - }); + { + Predicate = _ => true, + ResponseWriter = Shared.HealthChecks.HealthCheckMiddleware.WriteResponse + }); endpoints.MapHealthChecks("healthui", new HealthCheckOptions() - { - Predicate = _ => true, - ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse - }); + { + Predicate = _ => true, + ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse + }); }); app.UseSwagger(); diff --git a/MessagingService/appsettings.json b/MessagingService/appsettings.json index 76940ca..85fcc93 100644 --- a/MessagingService/appsettings.json +++ b/MessagingService/appsettings.json @@ -21,7 +21,8 @@ }, "EmailProxy": "Smtp2Go", "SMSProxy": "TheSMSWorks", - "SMTP2GoBaseAddress": "https://api.smtp2go.com/v3/", + //"SMTP2GoBaseAddress": "https://api.smtp2go.com/v3/", + "SMTP2GoBaseAddress": "https://httpbin.org", "SMTP2GoAPIKey": "api-FC9777E0E53611E6A2F3F23C91BBF4A0", "TheSMSWorksBaseAddress": "https://api.thesmsworks.co.uk/v1/", "TheSMSWorksCustomerId": "5400-d666-5990-402f-aa48-a1fa9f45fd02", diff --git a/MessagingService/nlog.config b/MessagingService/nlog.config index d45c238..f87e8b1 100644 --- a/MessagingService/nlog.config +++ b/MessagingService/nlog.config @@ -5,7 +5,7 @@ - +