예제 #1
0
        public Task <ServiceStatus> GetCurrentStatusAsync()
        {
            var serviceStatus = new ServiceStatus {
                Name = ServiceName, Status = ServiceState.Red, CheckCorrelationId = Guid.NewGuid()
            };

            var emailAddress       = "*****@*****.**";
            var vocPersonalisation = new VocSurveyPersonalisation();

            vocPersonalisation.Personalisation.Add("jpprofile", "ServiceCheck");
            vocPersonalisation.Personalisation.Add("clientId", "ServiceCheck ClientId");
            try
            {
                var response = clientProxy.SendEmail(ConfigurationManager.AppSettings[Constants.GovUkNotifyApiKey], emailAddress, ConfigurationManager.AppSettings[Constants.GovUkNotifyTemplateId], this.Convert(vocPersonalisation));

                //Got a response back
                serviceStatus.Status = ServiceState.Amber;
                if (!string.IsNullOrEmpty(response?.id))
                {
                    serviceStatus.Status             = ServiceState.Green;
                    serviceStatus.CheckCorrelationId = Guid.Empty;
                }
                else
                {
                    applicationLogger.Warn($"{nameof(GovUkNotifyService)}.{nameof(GetCurrentStatusAsync)} : {Constants.ServiceStatusWarnLogMessage} - Correlation Id [{serviceStatus.CheckCorrelationId}] - Email used [{emailAddress}]");
                }
            }
            catch (Exception ex)
            {
                applicationLogger.ErrorJustLogIt($"{nameof(GovUkNotifyService)}.{nameof(GetCurrentStatusAsync)} : {Constants.ServiceStatusFailedLogMessage} - Correlation Id [{serviceStatus.CheckCorrelationId}] - Email used [{emailAddress}]", ex);
            }

            return(Task.FromResult(serviceStatus));
        }
예제 #2
0
        public async Task <ServiceStatus> GetCurrentStatusAsync()
        {
            var serviceStatus = new ServiceStatus {
                Name = ServiceName, Status = ServiceState.Red, CheckCorrelationId = Guid.NewGuid()
            };
            var checkSubject = "maths";

            try
            {
                var request   = MessageConverter.GetCourseListInput(checkSubject);
                var apiResult = await serviceHelper.UseAsync <ServiceInterface, CourseListOutput>(async x => await tolerancePolicy.ExecuteAsync(() => x.CourseListAsync(request), Constants.CourseSearchEndpointConfigName, FaultToleranceType.CircuitBreaker), Constants.CourseSearchEndpointConfigName);

                //The call worked ok
                serviceStatus.Status = ServiceState.Amber;

                //We have actual data
                if (apiResult.CourseListResponse.CourseDetails.Any())
                {
                    serviceStatus.Status             = ServiceState.Green;
                    serviceStatus.CheckCorrelationId = Guid.Empty;
                }
                else
                {
                    applicationLogger.Warn($"{nameof(CourseSearchService)}.{nameof(GetCurrentStatusAsync)} : {Constants.ServiceStatusWarnLogMessage} - Correlation Id [{serviceStatus.CheckCorrelationId}] - Searched for [{checkSubject}]");
                }
            }
            catch (Exception ex)
            {
                applicationLogger.ErrorJustLogIt($"{nameof(CourseSearchService)}.{nameof(GetCurrentStatusAsync)} : {Constants.ServiceStatusFailedLogMessage} - Correlation Id [{serviceStatus.CheckCorrelationId}] - Searched for [{checkSubject}]", ex);
            }

            return(serviceStatus);
        }
 private IAsyncPolicy GetContextualAsyncPolicy()
 {
     return(Policy.CacheAsync(
                memoryCacheProvider,
                new ContextualTtl(),
                new DefaultCacheKeyStrategy(),
                onCachePut: (context, key) => logger.Trace($"Caching '{key}'."),
                onCacheGet: (context, key) => logger.Trace($"Retrieving '{key}' from the cache."),
                onCachePutError: (context, key, exception) => logger.ErrorJustLogIt($"Cannot add '{key}' to the cache.", exception),
                onCacheGetError: (context, key, exception) => logger.ErrorJustLogIt($"Cannot retrieve '{key}' from the cache.", exception),
                onCacheMiss: (context, key) => logger.Trace($"Cache miss for '{key}'.")));
 }
        public void ExportCompositePageExceptionTest()
        {
            //Setup
            A.CallTo(() => fakeApplicationLogger.ErrorJustLogIt(A <string> ._, A <Exception> ._)).DoesNothing();
            A.CallTo(() => fakeDataEventActions.GetEventAction(A <IDataEvent> ._)).Throws(new ArgumentException());

            //Act
            var dataEventHandler = new DataEventProcessor(fakeApplicationLogger, fakeCompositePageBuilder, fakeAsyncHelper, fakeDataEventActions, fakeDynamicContentConverter, fakeServiceBusMessageProcessor, fakeDynamicContentExtensions, fakeDynamicContentAction, fakeSitefinityManagerProxy);

            //Asserts
            Assert.Throws <ArgumentException>(() => dataEventHandler.ExportCompositePage(fakeDataEvent));

            A.CallTo(() => fakeApplicationLogger.ErrorJustLogIt(A <string> ._, A <Exception> ._)).MustHaveHappenedOnceExactly();
        }
        public async Task <JobProfileSalary> GetSalaryBySocAsync(string socCode)
        {
            if (socCode == null)
            {
                throw new ArgumentNullException(nameof(socCode));
            }

            try
            {
                // Four digit soccode
                var fourDigitSocCode = socCode.Substring(0, 4);
                var response         = await asheProxy.EstimatePayMdAsync(fourDigitSocCode);

                if (response.IsSuccessStatusCode)
                {
                    return(await response.Content.ReadAsAsync <JobProfileSalary>());
                }
                else
                {
                    applicationLogger.Warn($"Failed to get the salary information from LMI feed. StatusCode: {response.StatusCode} Reason: {response.ReasonPhrase} Content: {await response.Content.ReadAsStringAsync()}");
                    return(null);
                }
            }
            catch (Exception ex)
            {
                applicationLogger.ErrorJustLogIt($"Failed to get the salary information from LMI feed.", ex);
                return(null);
            }
        }
        public async Task <IEnumerable <Course> > GetCoursesAsync(string jobProfileKeywords)
        {
            if (jobProfileKeywords == null)
            {
                return(null);
            }

            var request = MessageConverter.GetCourseListInput(jobProfileKeywords);

            auditRepository.CreateAudit(request);

            //if the the call to the courses API fails for anyreason we should log and continue as if there are no courses available.
            try
            {
                var apiResult = await serviceHelper.UseAsync <ServiceInterface, CourseListOutput>(async x => await tolerancePolicy.ExecuteAsync(() => x.CourseListAsync(request), Constants.CourseSearchEndpointConfigName, FaultToleranceType.CircuitBreaker), Constants.CourseSearchEndpointConfigName);

                auditRepository.CreateAudit(apiResult);
                var result         = apiResult?.ConvertToCourse();
                var filteredResult = courseOpportunityBuilder.SelectCoursesForJobProfile(result);
                return(filteredResult);
            }
            catch (Exception ex)
            {
                auditRepository.CreateAudit(ex);
                applicationLogger.ErrorJustLogIt("Getting courses Failed - ", ex);
                return(Enumerable.Empty <Course>());
            }
        }
        public async Task <ServiceStatus> GetCurrentStatusAsync()
        {
            var serviceStatus = new ServiceStatus {
                Name = ServiceName, Status = ServiceState.Red, CheckCorrelationId = Guid.NewGuid()
            };
            var checkSubject = "maths";

            try
            {
                var apiResult = await apiService.GetCoursesAsync(checkSubject).ConfigureAwait(false);

                //The call worked ok
                serviceStatus.Status = ServiceState.Amber;

                //We have actual data
                if (apiResult.Any())
                {
                    serviceStatus.Status             = ServiceState.Green;
                    serviceStatus.CheckCorrelationId = Guid.Empty;
                }
                else
                {
                    applicationLogger.Warn($"{nameof(CourseSearchService)}.{nameof(GetCurrentStatusAsync)} : {Constants.ServiceStatusWarnLogMessage} - Correlation Id [{serviceStatus.CheckCorrelationId}] - Searched for [{checkSubject}]");
                }
            }
            catch (Exception ex)
            {
                applicationLogger.ErrorJustLogIt($"{nameof(CourseSearchService)}.{nameof(GetCurrentStatusAsync)} : {Constants.ServiceStatusFailedLogMessage} - Correlation Id [{serviceStatus.CheckCorrelationId}] - Searched for [{checkSubject}]", ex);
            }

            return(serviceStatus);
        }
        public async Task <ServiceStatus> GetCurrentStatusAsync()
        {
            var serviceStatus = new ServiceStatus {
                Name = ServiceName, Status = ServiceState.Red, CheckCorrelationId = Guid.NewGuid()
            };
            var searchTerm = "*";

            try
            {
                var searchParam = new SearchParameters {
                    Top = 5
                };
                var result = await indexClient.Documents.SearchAsync <T>(searchTerm, searchParam);

                //The call worked ok
                serviceStatus.Status = ServiceState.Amber;

                if (result.Results.Count > 0)
                {
                    serviceStatus.Status             = ServiceState.Green;
                    serviceStatus.CheckCorrelationId = Guid.Empty;
                }
                else
                {
                    applicationLogger.Warn($"{nameof(AzSearchQueryService<T>)}.{nameof(GetCurrentStatusAsync)} : {Constants.ServiceStatusWarnLogMessage} - Correlation Id [{serviceStatus.CheckCorrelationId}] - Search term used [{searchTerm}]");
                }
            }
            catch (Exception ex)
            {
                applicationLogger.ErrorJustLogIt($"{nameof(AzSearchQueryService<T>)}.{nameof(GetCurrentStatusAsync)} : {Constants.ServiceStatusFailedLogMessage} - Correlation Id [{serviceStatus.CheckCorrelationId}] - Search term used [{searchTerm}]", ex);
            }

            return(serviceStatus);
        }
        public async Task <JobProfileSalary> PopulateSalary(string socCode, string jobProfileUrlName)
        {
            applicationLogger.Trace($"BEGIN: Method '{nameof(PopulateSalary)}' called from '{nameof(JobProfileIndexEnhancer)}' with parameters '{socCode}'.");
            JobProfileSalary salary = new JobProfileSalary();

            try
            {
                salary = await salaryService.GetSalaryBySocAsync(socCode);

                salary.JobProfileName    = jobProfileUrlName;
                salary.StarterSalary     = Convert.ToDouble(salaryCalculator.GetStarterSalary(salary));
                salary.SalaryExperienced = Convert.ToDouble(salaryCalculator.GetExperiencedSalary(salary));

                if (salary.StarterSalary == 0 || salary.SalaryExperienced == 0)
                {
                    applicationLogger.Warn($"ERROR: Method '{nameof(PopulateSalary)}' called from '{nameof(JobProfileIndexEnhancer)}' with parameters '{socCode}' failed to get salary '{JsonConvert.SerializeObject(salary)}'.");
                }
            }
            catch (Exception ex)
            {
                //If there is a failure for this profile, log and continue with other profiles
                applicationLogger.ErrorJustLogIt($"ERROR: Method '{nameof(PopulateSalary)}' called from '{nameof(JobProfileIndexEnhancer)}' with parameters '{socCode}' failed with exception '{ex.Message}'.", ex);
            }
            finally
            {
                salary.JobProfileName = jobProfileUrlName;
                applicationLogger.Trace($"END: Method '{nameof(PopulateSalary)}' called from '{nameof(JobProfileIndexEnhancer)}' with parameters '{socCode}' returned {JsonConvert.SerializeObject(salary)}.");
            }

            return(salary);
        }
예제 #10
0
        public void SubmitEmail(string responseId, bool throwError, bool expectation)
        {
            //Fakes
            string emailAddress  = "*****@*****.**";
            var    emailResponse = responseId == null ? null : new Notify.Models.Responses.EmailNotificationResponse
            {
                id = responseId
            };

            //Configure calls
            if (throwError)
            {
                A.CallTo(() => fakeGovUkNotifyClient.SendEmail(A <string> ._, A <string> ._, A <string> ._, A <Dictionary <string, dynamic> > ._)).Throws <NotifyClientException>();
            }
            else
            {
                A.CallTo(() => fakeGovUkNotifyClient.SendEmail(A <string> ._, A <string> ._, A <string> ._, A <Dictionary <string, dynamic> > ._)).Returns(emailResponse);
            }

            //Act
            var govUkNotifyService = new GovUkNotifyService(fakeApplicationLogger, fakeGovUkNotifyClient);
            var result             = govUkNotifyService.SubmitEmail(emailAddress, new VocSurveyPersonalisation());

            //Assertions
            result.Should().Be(expectation);
            A.CallTo(() => fakeGovUkNotifyClient.SendEmail(A <string> ._, A <string> .That.IsEqualTo(emailAddress), A <string> ._, A <Dictionary <string, dynamic> > ._)).MustHaveHappened();
            if (throwError)
            {
                A.CallTo(() => fakeApplicationLogger.ErrorJustLogIt(A <string> ._, A <Exception> ._)).MustHaveHappened();
            }
        }
        public async Task <ServiceStatus> GetCurrentStatusAsync()
        {
            var serviceStatus = new ServiceStatus {
                Name = ServiceName, Status = ServiceState.Red, CheckCorrelationId = Guid.NewGuid()
            };

            try
            {
                var response = await this.httpPublishingClient.GetAsync(configurationProvider.GetConfig <string>(Constants.CUIShellHealthEndPoint));

                if (response.IsSuccessStatusCode)
                {
                    // Got a response back
                    serviceStatus.Status             = ServiceState.Green;
                    serviceStatus.CheckCorrelationId = Guid.Empty;
                }
                else
                {
                    applicationLogger.Warn($"{nameof(CUIShellHealthCheck)}.{nameof(GetCurrentStatusAsync)} : {Constants.ServiceStatusWarnLogMessage} - Correlation Id [{serviceStatus.CheckCorrelationId}] - Non Success Response StatusCode [{response.StatusCode}] Reason [{response.ReasonPhrase}]");
                }
            }
            catch (Exception ex)
            {
                applicationLogger.ErrorJustLogIt($"{nameof(CUIShellHealthCheck)}.{nameof(GetCurrentStatusAsync)} : {Constants.ServiceStatusFailedLogMessage} - Correlation Id [{serviceStatus.CheckCorrelationId}]", ex);
            }

            return(serviceStatus);
        }
        public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter)
        {
            switch (logLevel)
            {
            case LogLevel.Information:
                applicationLogger.Info($"{nameof(CourseSearchLogger<T>)}-{typeof(T)}-EventId:{eventId}-Formatted:{formatter(state, exception)}");
                break;

            case LogLevel.Warning:
                applicationLogger.Warn($"{nameof(CourseSearchLogger<T>)}-EventId:{eventId}-Formatted:{formatter(state, exception)}");
                break;

            case LogLevel.Critical:
            case LogLevel.Error:
                applicationLogger.ErrorJustLogIt($"{nameof(CourseSearchLogger<T>)}-{typeof(T)}-EventId:{eventId}-Formatted:{formatter(state, exception)}", exception);
                break;

            case LogLevel.None:
            case LogLevel.Trace:
            case LogLevel.Debug:
            default:
                applicationLogger.Trace($"{nameof(CourseSearchLogger<T>)}-{typeof(T)}-EventId:{eventId}-Formatted:{formatter(state, exception)}");
                break;
            }
        }
예제 #13
0
 private void SetupCalls()
 {
     A.CallTo(() => fakeApplicationLogger.Info(A <string> ._)).DoesNothing();
     A.CallTo(() => fakeApplicationLogger.ErrorJustLogIt(A <string> ._, A <Exception> ._)).DoesNothing();
     A.CallTo(() => fakeApplicationLogger.Trace(A <string> ._)).DoesNothing();
     A.CallTo(() => fakeAccountsService.OpenCircuitBreakerAsync()).Returns(Task.CompletedTask);
     A.CallTo(() => fakeAccountsService.HalfOpenCircuitBreakerAsync()).Returns(Task.CompletedTask);
     A.CallTo(() => fakeAccountsService.InsertAuditAsync(A <AccountNotificationAudit> ._)).Returns(Task.CompletedTask);
     A.CallTo(() => fakeAccountsService.SetBatchToCircuitGotBrokenAsync(A <IEnumerable <Account> > ._)).Returns(Task.CompletedTask);
     A.CallTo(() => fakeAccountsService.CloseCircuitBreakerAsync()).Returns(Task.CompletedTask);
 }
예제 #14
0
 private Policy GetCircuitBreaker(string dependency)
 {
     return(Policy
            .Handle <Exception>()
            .CircuitBreaker(
                exceptionsAllowedBeforeBreaking: strategy.AllowedFaults,
                durationOfBreak: strategy.Breaktime,
                onBreak: (ex, breakDelay) => logger.ErrorJustLogIt($"{nameof(TolerancePolicy)}:Circuit-Breaker logging: Broken : {dependency}: Breaking the circuit for {breakDelay}, failure-{ex.Message}", ex),
                onReset: () => logger.Info($"{nameof(TolerancePolicy)}:Circuit-Breaker logging: {dependency}: Call succeeded. Closed the circuit again!"),
                onHalfOpen: () => logger.Warn($"{nameof(TolerancePolicy)}:Circuit-Breaker logging: {dependency}: Half-open: Next call is a trial!")));
 }
 /// <summary>
 /// Submits the email.
 /// </summary>
 /// <param name="emailAddress">The email address.</param>
 /// <param name="vocPersonalisation">Stores dictionary of jpprofile and clientid</param>
 /// <returns>true or false</returns>
 public bool SubmitEmail(string emailAddress, VocSurveyPersonalisation vocPersonalisation)
 {
     try
     {
         var response = clientProxy.SendEmail(ConfigurationManager.AppSettings[Constants.GovUkNotifyApiKey], emailAddress, ConfigurationManager.AppSettings[Constants.GovUkNotifyTemplateId], this.Convert(vocPersonalisation));
         return(!string.IsNullOrEmpty(response?.id));
     }
     catch (NotifyClientException ex)
     {
         applicationLogger.ErrorJustLogIt("Failed to send VOC email", ex);
         return(false);
     }
 }
        public async Task CreateAuditExceptionTest()
        {
            //Arrange
            var dummyContactUsRequest             = A.Dummy <ContactUsRequest>();
            var dummyEmailTemplate                = A.Dummy <EmailTemplate>();
            var dummyResponse                     = A.Dummy <SendEmailResponse>();
            var fakeErrorMergeEmailContentService = A.Fake <IMergeEmailContent <ContactUsRequest> >();
            var repo = new EmailAuditRepository <ContactUsRequest>(fakeConfiguration, fakeDocumentClient, fakeErrorMergeEmailContentService, fakeLogger)
            {
                Database           = "db",
                DocumentCollection = "docCollection"
            };

            A.CallTo(() => fakeErrorMergeEmailContentService.MergeTemplateBodyWithContent(A <ContactUsRequest> ._, A <string> ._)).Throws <NullReferenceException>();
            A.CallTo(() => fakeLogger.ErrorJustLogIt(A <string> ._, A <Exception> ._)).DoesNothing();

            //Act
            repo.CreateAudit(dummyContactUsRequest, dummyEmailTemplate, dummyResponse);
            await Task.Delay(10);

            //Assert
            A.CallTo(() => fakeDocumentClient.CreateDocumentAsync(A <Uri> ._, A <Audit> .That.Matches(m => ((EmailAuditRecord <ContactUsRequest>)m.Data).Exception is NullReferenceException), A <RequestOptions> ._, A <bool> ._, A <CancellationToken> ._)).MustHaveHappened();
            A.CallTo(() => fakeLogger.ErrorJustLogIt(A <string> ._, A <Exception> ._)).MustHaveHappened();
        }
예제 #17
0
        public async Task GetServiceStatusExceptionAsync()
        {
            //Arrange
            //add no content to cause an exception
            var httpResponseMessage = new HttpResponseMessage();

            A.CallTo(() => fakeHttpClientService.PostAsync(A <string> ._, A <string> ._, A <FaultToleranceType> ._)).Throws(new HttpRequestException());

            //Act
            var shellHealthCheck = new CUIShellHealthCheck(fakeApplicationLogger, fakeConfigurationProvider, fakeHttpClientService);
            var serviceStatus    = await shellHealthCheck.GetCurrentStatusAsync();

            //Asserts
            serviceStatus.Status.Should().NotBe(ServiceState.Green);
            A.CallTo(() => fakeApplicationLogger.ErrorJustLogIt(A <string> ._, A <Exception> ._)).MustHaveHappened();
        }
예제 #18
0
        public async Task <ServiceStatus> GetCurrentStatusAsync()
        {
            const string ServiceName   = "FAM Area Routing API";
            const string DummyPostcode = "CV1 2WT";

            var serviceStatus = new ServiceStatus {
                Name = ServiceName, Status = ServiceState.Red, CheckCorrelationId = Guid.NewGuid()
            };

            try
            {
                var url       = $"{configuration.GetConfig<string>(Constants.AreaRoutingApiServiceUrl)}?location={DummyPostcode}";
                var accessKey = configuration.GetConfig <string>(Constants.AreaRoutingApiSubscriptionKey);

                httpClientService.AddHeader(Constants.OcpApimSubscriptionKey, accessKey);
                var response = await this.httpClientService.GetAsync(url);

                if (response.IsSuccessStatusCode)
                {
                    var areaRoutingApiResponse = await response.Content.ReadAsAsync <AreaRoutingApiResponse>();

                    if (!string.IsNullOrWhiteSpace(areaRoutingApiResponse.EmailAddress))
                    {
                        serviceStatus.Status             = ServiceState.Green;
                        serviceStatus.CheckCorrelationId = Guid.Empty;
                    }
                    else
                    {
                        serviceStatus.Status = ServiceState.Amber;
                        applicationLogger.Warn($"{nameof(FamSendGridEmailService)}.{nameof(GetCurrentStatusAsync)} : {Constants.ServiceStatusWarnLogMessage} - Correlation Id [{serviceStatus.CheckCorrelationId}] - Called using postcode [{DummyPostcode}], Received email address [{areaRoutingApiResponse.EmailAddress}], Api Response was [{response.StatusCode}]");
                    }
                }
                else
                {
                    applicationLogger.Error($"{nameof(FamSendGridEmailService)}.{nameof(GetCurrentStatusAsync)} : {Constants.ServiceStatusFailedLogMessage} - Correlation Id [{serviceStatus.CheckCorrelationId}] - Called using postcode [{DummyPostcode}]. Api Response was [{response.StatusCode}], [{response.ReasonPhrase}]");
                }
            }
            catch (Exception e)
            {
                applicationLogger.ErrorJustLogIt($"{nameof(FamSendGridEmailService)}.{nameof(GetCurrentStatusAsync)} : {Constants.ServiceStatusFailedLogMessage} - Correlation Id [{serviceStatus.CheckCorrelationId}] - Called using postcode [{DummyPostcode}]", e);
            }

            return(serviceStatus);
        }
        public async Task <ServiceStatus> GetCurrentCUIAppStatusAsync(string serviceName, string serviceEndPoint)
        {
            var serviceStatus = new ServiceStatus {
                Name = serviceName, Status = ServiceState.Red, CheckCorrelationId = Guid.NewGuid()
            };

            try
            {
                this.httpClient.AddHeader("Accept", "application/json");
                var response = await this.httpClient.GetAsync(serviceEndPoint);

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    serviceStatus.Status = ServiceState.Amber;
                    var responseString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                    var cuiHealthStatuses = JsonConvert.DeserializeObject <IList <ServiceStatusCUIResponse> >(responseString);
                    serviceStatus.ChildAppStatuses = new List <ServiceStatusChildApp>();
                    foreach (ServiceStatusCUIResponse s in cuiHealthStatuses)
                    {
                        serviceStatus.ChildAppStatuses.Add(new ServiceStatusChildApp()
                        {
                            Name = s.Service, Status = s.Message.Contains("is available") ? ServiceState.Green : ServiceState.Red
                        });
                    }

                    if (serviceStatus.ChildAppStatuses.All(s => s.Status == ServiceState.Green))
                    {
                        serviceStatus.Status             = ServiceState.Green;
                        serviceStatus.CheckCorrelationId = Guid.Empty;
                    }
                }
                else
                {
                    applicationLogger.Warn($"{nameof(CUIJobprofilesHealthCheck)}.{nameof(GetCurrentCUIAppStatusAsync)} : {Constants.ServiceStatusWarnLogMessage} - Correlation Id [{serviceStatus.CheckCorrelationId}] - Non Success Response StatusCode [{response.StatusCode}] Reason [{response.ReasonPhrase}]");
                }
            }
            catch (Exception ex)
            {
                applicationLogger.ErrorJustLogIt($"{nameof(CUIJobprofilesHealthCheck)}.{nameof(GetCurrentCUIAppStatusAsync)} : {Constants.ServiceStatusFailedLogMessage} - Correlation Id [{serviceStatus.CheckCorrelationId}]", ex);
            }

            return(serviceStatus);
        }
        private async Task <string> GetFileHashAsync(string assetLocation)
        {
            try
            {
                var response = await httpClientService.GetAsync(assetLocation);

                if (response.IsSuccessStatusCode)
                {
                    var hashCode = response.Content.Headers.GetValues(ContentMDS).FirstOrDefault();
                    return(!string.IsNullOrWhiteSpace(hashCode) ? hashCode.Replace("-", string.Empty) : DateTime.Now.ToString("yyyyMMddHH"));
                }
            }
            catch (Exception ex)
            {
                applicationLogger.ErrorJustLogIt("Failed to get file hash", ex);
            }

            //If we dont get a valid response use the current time to the nearest hour.
            return(DateTime.Now.ToString("yyyyMMddHH"));
        }
        public void CreateAudit(T emailRequest, EmailTemplate emailTemplate, SendEmailResponse response)
        {
            var safeRequestSerialized = JsonConvert.SerializeObject(emailRequest);
            var safeRequest           = JsonConvert.DeserializeObject <T>(safeRequestSerialized);

            try
            {
                var emailContent = mergeEmailContentService.MergeTemplateBodyWithContent(safeRequest, emailTemplate?.Body);
                Add(new Audit
                {
                    CorrelationId = correlationId,
                    Data          = new EmailAuditRecord <T>
                    {
                        Request           = safeRequest,
                        EmailContent      = emailContent,
                        SendEmailResponse = response,
                        EmailTemplate     = emailTemplate
                    },
                    Timestamp = DateTime.Now
                });
            }
            catch (Exception exception)
            {
                logger.ErrorJustLogIt($"Failed to audit non-citizen email", exception);
                Add(new Audit
                {
                    CorrelationId = correlationId,
                    Data          = new EmailAuditRecord <T>
                    {
                        Request           = safeRequest,
                        Exception         = exception,
                        SendEmailResponse = response,
                        EmailTemplate     = emailTemplate
                    },
                    Timestamp = DateTime.Now
                });
            }
        }
        public async Task <ServiceStatus> GetCurrentStatusAsync()
        {
            var serviceStatus = new ServiceStatus {
                Name = ServiceName, Status = ServiceState.Red, CheckCorrelationId = Guid.NewGuid()
            };
            var checkText = "nursee";

            try
            {
                var response = await GetSpellCheckResponseAsync(checkText);

                if (response.IsSuccessStatusCode)
                {
                    //Got a response back
                    serviceStatus.Status = ServiceState.Amber;
                    var resultsString = await response.Content.ReadAsStringAsync();

                    dynamic spellSuggestions = JObject.Parse(resultsString);
                    if (spellSuggestions.flaggedTokens.Count > 0)
                    {
                        //got corrections
                        serviceStatus.Status             = ServiceState.Green;
                        serviceStatus.CheckCorrelationId = Guid.Empty;
                    }
                }
                else
                {
                    applicationLogger.Warn($"{nameof(SpellCheckService)}.{nameof(GetCurrentStatusAsync)} : {Constants.ServiceStatusWarnLogMessage} - Correlation Id [{serviceStatus.CheckCorrelationId}] - Text used [{checkText}] - Unsuccessful reason [{response.ReasonPhrase} - {await response.Content.ReadAsStringAsync()}]");
                }
            }
            catch (Exception ex)
            {
                applicationLogger.ErrorJustLogIt($"{nameof(SpellCheckService)}.{nameof(GetCurrentStatusAsync)} : {Constants.ServiceStatusFailedLogMessage} - Correlation Id [{serviceStatus.CheckCorrelationId}] - Text used [{checkText}]", ex);
            }

            return(serviceStatus);
        }
예제 #23
0
        public void PublishDynamicContent(DynamicContent item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("eventInfo");
            }

            DynamicModuleManager dynamicModuleManager = DynamicModuleManager.GetManager(Constants.DynamicProvider);
            var eventAction = dynamicContentAction.GetDynamicContentEventAction(item);

            //using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"\logs\logger.txt", true))
            //{
            //    //file.WriteLine($"\n| Dynamic Content Action Type - | {eventActionType.PadRight(10, ' ')}");
            //    file.WriteLine($" |Item Type -- {item.GetType().Name.PadRight(10, ' ')} |Item ID -- {item.Id.ToString().PadRight(15, ' ')} | Item ApprovalWorkflowState -- {item.ApprovalWorkflowState.Value.PadRight(15, ' ')} | Item Status -- {item.Status.ToString().PadRight(10, ' ')} | Item Triggered action - {eventActionType.PadRight(10, ' ')} |");
            //    file.WriteLine($"*********************************************************************************************************************************************************\n");
            //}
            applicationLogger.Trace($"Got event - |{item.GetType().Name.PadRight(15, ' ')} -- {item.Id.ToString().PadRight(15, ' ')} |{item.ApprovalWorkflowState.Value.PadRight(15, ' ')} | {item.Status.ToString().PadRight(15, ' ')} | Derived action - {eventAction.ToString().PadRight(15, ' ')}");

            try
            {
                if (eventAction == MessageAction.Ignored)
                {
                    return;
                }

                switch (item.GetType().Name)
                {
                case Constants.JobProfile:
                    if (eventAction == MessageAction.Published || eventAction == MessageAction.Draft)
                    {
                        GenerateServiceBusMessageForJobProfile(item, eventAction);
                    }
                    else
                    {
                        GenerateServiceBusMessageForJobProfileUnPublish(item, eventAction);
                    }

                    break;

                case Constants.Restriction:
                case Constants.Registration:
                case Constants.ApprenticeshipRequirement:
                case Constants.CollegeRequirement:
                case Constants.UniversityRequirement:
                    GenerateServiceBusMessageForInfoTypes(item, eventAction);

                    break;

                case Constants.Uniform:
                case Constants.Location:
                case Constants.Environment:
                    GenerateServiceBusMessageForWYDTypes(item, eventAction);

                    break;

                case Constants.UniversityLink:
                case Constants.CollegeLink:
                case Constants.ApprenticeshipLink:
                    GenerateServiceBusMessageForTextFieldTypes(item, eventAction);

                    break;

                case Constants.Skill:
                    GenerateServiceBusMessageForSkillTypes(item, eventAction);

                    break;

                case Constants.JobProfileSoc:
                    GenerateServiceBusMessageForSocCodeType(item, eventAction);

                    break;

                case Constants.SOCSkillsMatrix:

                    //For all the Dynamic content types we are using Jobprofile as Parent Type
                    //and for only Skills we are using SocSkillsMatrix Type as the Parent Type
                    var liveVersionItem = item;

                    if (item.Status.ToString() != Constants.ItemStatusLive)
                    {
                        var liveItem = dynamicModuleManager.Lifecycle.GetLive(item);
                        liveVersionItem = dynamicModuleManager.GetDataItem(item.GetType(), liveItem.Id);
                    }
                    else
                    {
                        var masterItem = dynamicModuleManager.Lifecycle.GetMaster(item);
                        item = dynamicModuleManager.GetDataItem(item.GetType(), masterItem.Id);
                    }

                    SkillsMatrixParentItems = GetParentItemsForSocSkillsMatrix(item);
                    GenerateServiceBusMessageForSocSkillsMatrixType(liveVersionItem, item, eventAction);

                    break;

                default:
                    break;
                }
            }
            catch (Exception ex)
            {
                applicationLogger.ErrorJustLogIt($"Failed to export data for item id {item.Id}", ex);
                throw;
            }
        }
        private async Task SendNextBatchOfEmailsAsync()
        {
            var circuitBreaker = await accountsService.GetCircuitBreakerStatusAsync();

            if (circuitBreaker.CircuitBreakerStatus != CircuitBreakerStatus.Open)
            {
                var batchSize = configuration.GetConfig <int>(Constants.BatchSize);

                var emailBatch = await accountsService.GetNextBatchOfEmailsAsync(batchSize);

                var accountsToProcess = emailBatch.ToList();
                applicationLogger.Trace($"About to process email notifications with a batch size of {accountsToProcess.Count}");

                var halfOpenCountAllowed = configuration.GetConfig <int>(Constants.GovUkNotifyRetryCount);

                foreach (var account in accountsToProcess)
                {
                    try
                    {
                        var serviceResponse = await sendCitizenNotificationService.SendCitizenNotificationAsync(account);

                        if (serviceResponse.RateLimitException)
                        {
                            await accountsService.OpenCircuitBreakerAsync();

                            applicationLogger.Info(
                                $"RateLimit Exception thrown now resetting the unprocessed email notifications");

                            await accountsService.SetBatchToCircuitGotBrokenAsync(
                                accountsToProcess.Where(notification => !notification.Processed));

                            break;
                        }

                        await accountsService.InsertAuditAsync(new AccountNotificationAudit
                        {
                            Email = account.EMail,
                            NotificationProcessingStatus = serviceResponse.Success
                                ? NotificationProcessingStatus.Completed
                                : NotificationProcessingStatus.Failed
                        });

                        if (serviceResponse.Success &&
                            circuitBreaker.CircuitBreakerStatus == CircuitBreakerStatus.HalfOpen)
                        {
                            await accountsService.CloseCircuitBreakerAsync();
                        }

                        account.Processed = true;
                    }
                    catch (Exception exception)
                    {
                        await accountsService.InsertAuditAsync(new AccountNotificationAudit
                        {
                            Email = account.EMail,
                            NotificationProcessingStatus = NotificationProcessingStatus.Failed,
                            Note = exception.InnerException?.Message
                        });

                        await accountsService.HalfOpenCircuitBreakerAsync();

                        applicationLogger.ErrorJustLogIt("Exception whilst sending email notification", exception);
                        circuitBreaker = await accountsService.GetCircuitBreakerStatusAsync();

                        if (circuitBreaker.CircuitBreakerStatus == CircuitBreakerStatus.HalfOpen &&
                            circuitBreaker.HalfOpenRetryCount == halfOpenCountAllowed)
                        {
                            await accountsService.OpenCircuitBreakerAsync();

                            //Set the all the accountsin the batch that did not get processed (sent ok)  to CircuitGotBroken
                            await accountsService.SetBatchToCircuitGotBrokenAsync(
                                accountsToProcess.Where(notification => !notification.Processed));

                            break;
                        }
                    }
                }

                applicationLogger.Trace("Completed processing all accounts in the batch");
            }
            else
            {
                applicationLogger.Info("Circuit is open so no account processed");
            }
        }