Ejemplo n.º 1
0
        private void AddEmployees()
        {
            var emp = new List <Employee>
            {
                new Employee {
                    EmployeeFullName = "Dave Test",
                    Address          = "Test Address",
                    PhoneNumber      = "1234567890",
                    Position         = "General_Manager",
                },
                new Employee {
                    EmployeeFullName = "John Test",
                    Address          = "Test Address 2",
                    PhoneNumber      = "4567890112",
                    Position         = "General_Manager"
                },
            };

            _appContext.Employees.AddRange(emp);
            try
            {
                _appContext.SaveChanges();
            }
            catch (Exception ex)
            {
                _logger.Error($"Could not save Employees {ex}");
            }
        }
Ejemplo n.º 2
0
        private async Task <string> PostInternal(Uri requestUri, T data)
        {
            using (var client = await GetHttpClientAsync())
            {
                var content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, CONTENT_TYPE);
                var result  = await client.PostAsync(requestUri, content);

                if (result.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                {
                    throw new UnauthorizedAccessException(result.ReasonPhrase);
                }

                logger.Info($"Posted to url - '{requestUri}', returned '{result.StatusCode}' and headers '{result.Headers}'.");
                var jsonContent = await result.Content.ReadAsStringAsync();

                await auditService.AuditAsync($"Posted to url - {requestUri} | Returned -{jsonContent}");

                if (!result.IsSuccessStatusCode)
                {
                    logger.Error($"Failed to POST url - '{requestUri}', returned '{result.StatusCode}' and headers '{result.Headers}' and content '{jsonContent}'.", new HttpRequestException(jsonContent));
                    throw new HttpRequestException(jsonContent);
                }

                return(jsonContent);
            }
        }
Ejemplo n.º 3
0
        public void Intercept(IInvocation invocation)
        {
            if (invocation != null)
            {
                try
                {
                    var returnType = invocation.Method.ReturnType;
                    if (returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(Task <>))
                    {
                        InterceptAsyncFunc(invocation);
                    }
                    else if (returnType == typeof(Task))
                    {
                        invocation.ReturnValue = InterceptAsyncAction(invocation);
                    }
                    else
                    {
                        InterceptSync(invocation);
                    }
                }
                catch (LoggedException)
                {
                    // Ignore already logged exceptions.
                    // We would loose the stack trace to the callee is that an issue?
                    throw;
                }

                // other exception policies as we go along.
                catch (Exception ex)
                {
                    loggingService.Error($"Async Method '{invocation.Method.Name}' called from '{invocation.TargetType.FullName}' with parameters '{string.Join(", ", invocation.Arguments.Select(a => (a ?? string.Empty).ToString()).ToArray())}' failed with exception.", ex);
                    throw;
                }
            }
        }
Ejemplo n.º 4
0
 public IActionResult GetAllEmployees()
 {
     try
     {
         var data = _appDal.GetData();
         ViewData["EmployeesList"] = data;
         return(PartialView("~/Views/Employee/_tableData.cshtml"));
     }
     catch (Exception ex)
     {
         _logger.Error($"error in getting data {ex}");
         return(null);
     }
 }
        public async Task <HttpStatusCode> DeleteAVsRecycleBinRecordsAsync(int numberToDelete)
        {
            using (var httpClient = await GetHttpClientAsync())
            {
                var clearRequestUrl = customApiConfig.GetClearRequestUrl();
                var deleteUri       = $"{clearRequestUrl}?count={numberToDelete}";

                applicationLogger.Trace($"Start - ClearAVsRecycleBin {clearRequestUrl.OriginalString} called with {numberToDelete} items, will be using uri - {deleteUri} to call delete functon.");
                var result = await httpClient.DeleteAsync(deleteUri);

                applicationLogger.Trace($"End - ClearAVsRecycleBin {clearRequestUrl.OriginalString} called with {numberToDelete} items: Result was {result.StatusCode}");
                HttpStatusCode returnCode = result.StatusCode;

                if (result.StatusCode != HttpStatusCode.OK && result.StatusCode != HttpStatusCode.PartialContent)
                {
                    var content = await result.Content?.ReadAsStringAsync();

                    returnCode = content.ToLower().Contains(nameof(System.UnauthorizedAccessException)) ? HttpStatusCode.Unauthorized : result.StatusCode;

                    var errorMessage = $"Got unexpected response code {returnCode} - {result.ReasonPhrase}";
                    applicationLogger.Error($"{errorMessage} - {content} from ClearAVsRecycleBin API request", new HttpRequestException(errorMessage));
                }

                return(returnCode);
            }
        }
Ejemplo n.º 6
0
        public async Task <string> GetAsync(string requestQueryString, RequestType requestType)
        {
            using (var clientProxy = new HttpClient())
            {
                clientProxy.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", _subscriptionKey);
                clientProxy.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header

                var requestRoute = requestType == RequestType.search ? $"{requestType.ToString()}?" : string.Empty;
                var fullRequest  = $"{_endpoint}/{requestRoute}{requestQueryString}";
                logger.Trace($"Getting API data for request :'{fullRequest}'");

                var response = await clientProxy.GetAsync(fullRequest);

                var responseContent = await response.Content?.ReadAsStringAsync();

                await auditService.AuditAsync(responseContent, requestQueryString);

                if (!response.IsSuccessStatusCode)
                {
                    logger.Error($"Error status {response.StatusCode},  Getting API data for request :'{fullRequest}' \nResponse : {responseContent}", null);
                    //this will throw an exception as is not a success code
                    await response.EnsureSuccessStatusCodeAsync();
                }
                return(responseContent);
            }
        }
        public async Task <SendNotificationResponse> SendCitizenNotificationAsync(Account notification)
        {
            var sendNotificationResponse = new SendNotificationResponse();

            try
            {
                var response = clientProxy.SendEmail(
                    configuration.GetConfig <string>(
                        Constants.GovUkNotifyApiKey),
                    notification.EMail,
                    configuration.GetConfig <string>(
                        Constants.GovUkNotifyTemplateId),
                    Convert(GetGovUkNotifyPersonalisation(notification)));

                sendNotificationResponse.Success = !string.IsNullOrEmpty(response?.id);
            }
            catch (NotifyClientException ex)
            {
                if (ex.Message.ToLowerInvariant()
                    .Contains(configuration.GetConfig <string>(
                                  Constants.GovUkNotifyRateLimitException)))
                {
                    sendNotificationResponse.RateLimitException = true;
                    await accountsService.OpenCircuitBreakerAsync();
                }

                applicationLogger.Error("Failed to send citizen email with GovUKNotify", ex);
            }

            return(sendNotificationResponse);
        }
        public async Task SendCitizenNotificationAsyncTests(string responseId, bool throwException, bool isRateLimitException, SendNotificationResponse expectation)
        {
            //Fakes
            var citizenEmailNotification = new Account
            {
                EMail = "*****@*****.**"
            };
            var emailResponse = responseId == null ? null : new Notify.Models.Responses.EmailNotificationResponse
            {
                id = responseId
            };

            //Configure calls
            if (throwException)
            {
                A.CallTo(() => fakeGovUkNotifyClient.SendEmail(A <string> ._, A <string> ._, A <string> ._, A <Dictionary <string, dynamic> > ._)).Throws(() => new NotifyClientException(isRateLimitException ? nameof(NotifyClientException).ToLowerInvariant() : nameof(Exception).ToLowerInvariant()));
            }
            else
            {
                A.CallTo(() => fakeGovUkNotifyClient.SendEmail(A <string> ._, A <string> ._, A <string> ._, A <Dictionary <string, dynamic> > ._)).Returns(emailResponse);
            }

            A.CallTo(() => fakeConfiguration.GetConfig <string>(A <string> ._)).Returns(isRateLimitException ? nameof(NotifyClientException).ToLowerInvariant() : "test");

            //Act
            var govUkNotifyService = new GovUkNotifyService(fakeApplicationLogger, fakeGovUkNotifyClient, fakeConfiguration, fakeAccountsService);
            var result             = await govUkNotifyService.SendCitizenNotificationAsync(citizenEmailNotification);

            //Assertions
            result.Should().BeEquivalentTo(expectation);
            A.CallTo(() => fakeGovUkNotifyClient.SendEmail(A <string> ._, A <string> .That.IsEqualTo(citizenEmailNotification.EMail), A <string> ._, A <Dictionary <string, dynamic> > ._)).MustHaveHappened();
            if (throwException)
            {
                A.CallTo(() => fakeApplicationLogger.Error(A <string> ._, A <Exception> ._)).MustHaveHappened();
                if (isRateLimitException)
                {
                    A.CallTo(() => fakeAccountsService.OpenCircuitBreakerAsync()).MustHaveHappened();
                }
            }
        }
 private async Task InterceptAsyncAction(IInvocation invocation)
 {
     try
     {
         invocation.Proceed();
         if (invocation.ReturnValue is Task task)
         {
             await task;
         }
     }
     catch (LoggedException)
     {
         // Ignore already logged exceptions.
         // We would loose the stack trace to the callee is that an issue?
         throw;
     }
     // other exception policies as we go along.
     catch (Exception ex)
     {
         loggingService.Error($"Async Method '{invocation.Method.Name}' called with parameters '{string.Join(", ", invocation.Arguments.Select(a => (a ?? "").ToString()).ToArray())}' failed with exception.", ex);
         throw;
     }
 }
Ejemplo n.º 10
0
        public override bool IndexExists(string indexName)
        {
            var activeIndex = string.Empty;

            try
            {
                if (!string.IsNullOrEmpty(indexName) && index.StartsWith(indexName, StringComparison.OrdinalIgnoreCase))
                {
                    activeIndex = index;
                    return(searchService.IndexExists(index));
                }
                else
                {
                    activeIndex = indexName;
                    return(base.IndexExists(indexName));
                }
            }
            catch (Exception exception)
            {
                applicationLogger.Error($" Method - {MethodBase.GetCurrentMethod().Name} on index {activeIndex} failed with an exception", exception);
            }

            return(false);
        }
Ejemplo n.º 11
0
 /// <summary>
 /// Run the application
 /// </summary>
 /// <param name="cancellationToken">The cancellation token</param>
 /// <returns>The task to run</returns>
 public async Task Run(CancellationToken cancellationToken)
 {
     try
     {
         await _application
         .Run(cancellationToken)
         .ConfigureAwait(Await.Default);
     }
     catch (OperationCanceledException)
     {
         if (_logger.IsErrorEnabled == true)
         {
             _logger.Error(LogResource.OperationCancellled);
         }
     }
 }
Ejemplo n.º 12
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);
        }
 private void LogFailedMessage(ServiceStatus serviceStatus, Exception ex)
 {
     serviceStatus.Notes = $"Service status check failed : {ex.Message}";
     Logger.Error($"Service status check failed", ex);
 }
 /// <summary>
 /// 写入一个error等级的日志记录.
 /// </summary>
 /// <param name="logger">日志记录器.</param>
 /// <param name="format">待格式化的消息字符串.</param>
 /// <param name="args">格式化参数列表.</param>
 public static void Error(this IApplicationLogger logger, String format, params Object[] args)
 {
     logger.Error(String.Format(format, args));
 }