Ejemplo n.º 1
0
        public JObject Decode(string secret, string token)
        {
            JObject result = null;

            if (!string.IsNullOrEmpty(token) && !string.IsNullOrEmpty(secret))
            {
                try
                {
                    result = JWT.Decode <JObject>(token, secret);
                }
                catch (IntegrityException)
                {
                    _logger.LogWarning("Integrity exception on passed token. Token is invalid");
                }
                catch (ArgumentOutOfRangeException)
                {
                    _logger.LogWarning("ArgumentOutOfRange exception on passed token. Token is invalid");
                }
                catch (IndexOutOfRangeException)
                {
                    _logger.LogWarning("IndexOutOfRange exception on passed token. Token is invalid");
                }
            }

            return(result);
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> Edit([FromQuery(Name = "categoryId")] int?id, [Bind("CategoryId", "CategoryName", "Description", "Picture")] CategoryEditViewModel edit)
        {
            if (!this.ModelState.IsValid)
            {
                _logger.LogWarning("Category model to edit is invalid. Redirecting to Index");

                return(View(edit));
            }
            try
            {
                _logger.LogInformation($"Started updating category model with id : {edit.CategoryId} ...");

                var mappedCategory = _mapper.Map <CategoryEditViewModel, CategoryUpdate>(edit);

                var updatedCategory = await _categoriesService.UpdateCategoryAsync <CategoryUpdate>(mappedCategory);

                var editViewModel = _mapper.Map <CategoryUpdate, CategoryEditViewModel>(updatedCategory);

                _logger.LogInformation($"Successfully finished updating category model with id : {edit.CategoryId} !");

                return(RedirectToAction("Index"));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Some error occured while processing request. See details.", null);

                return(View(edit));
            }
        }
Ejemplo n.º 3
0
        /// <inheritdoc/>
        /// <exception cref="ArgumentNullException">Raised if <paramref name="feedEntry"/> is null.</exception>
        /// <exception cref="ArgumentException">Raised if the content property of <param name="feedEntry"/> is null or empty.</exception>
        /// <exception cref="Azure.RequestFailedException">Raised if the XML contents cannot be saved to azure storage.</exception>
        public async Task <IList <ContractProcessResult> > ProcessEventsAsync(FeedEntry feedEntry)
        {
            if (feedEntry is null)
            {
                throw new ArgumentNullException(nameof(feedEntry));
            }

            if (string.IsNullOrWhiteSpace(feedEntry.Content))
            {
                throw new ArgumentException(nameof(feedEntry));
            }

            _loggerAdapter.LogInformation($"[{nameof(ProcessEventsAsync)}] - [Bookmark:{feedEntry.Id}] - Parsing xml string to object.");

            // XML is compatiable with the schema, so, it should deserialise.
            var contractEvents = await _deserilizationService.DeserializeAsync(feedEntry.Content);

            var resultsGroup = contractEvents
                               .GroupBy(c => c.Result)
                               .Select(g => $"{g.Key}:{g.Count()}");

            _loggerAdapter.LogInformation($"[{nameof(ProcessEventsAsync)}] - [Bookmark:{feedEntry.Id}] - XML parsing completed with results [{string.Join(",", resultsGroup)}].");

            try
            {
                foreach (var item in contractEvents)
                {
                    item.ContractEvent.BookmarkId = feedEntry.Id;

                    if (item.Result == ContractProcessResultType.Successful)
                    {
                        _loggerAdapter.LogInformation($"[{nameof(ProcessEventsAsync)}] - [Bookmark:{feedEntry.Id}] - Saving XML to azure strorage.");

                        // Save xml to blob
                        // Filename format : [Entry.Updated]_[ContractNumber]_v[ContractVersion]_[Entry.BookmarkId].xml
                        string filename = $"{feedEntry.Updated:yyyyMMddHHmmss}_{item.ContractEvent.ContractNumber}_v{item.ContractEvent.ContractVersion}_{item.ContractEvent.BookmarkId}.xml";

                        // Saved XML needs to be in lowercase to be compatible with the exisitng code on the monolith
                        var lowerCaseXmlString = ConvertToLowerCaseXml(item);

                        await _blobStorageService.UploadAsync(filename, Encoding.UTF8.GetBytes(lowerCaseXmlString));

                        item.ContractEvent.ContractEventXml = filename;

                        _loggerAdapter.LogInformation($"[{nameof(ProcessEventsAsync)}] - [Bookmark:{feedEntry.Id}] - Saving XML completed.");
                    }
                    else
                    {
                        _loggerAdapter.LogWarning($"[{nameof(ProcessEventsAsync)}] - [Bookmark:{feedEntry.Id}] - Ignoring filesave - Result is unsuccessful [{item.Result}].");
                    }
                }
            }
            catch (Exception ex)
            {
                _loggerAdapter.LogError(ex, $"Failed to save XML file for Bookmark [{feedEntry.Id}].");
                throw;
            }

            return(contractEvents);
        }
Ejemplo n.º 4
0
    private async Task <string> GetHostAddress(CancellationToken stoppingToken)
    {
        if (!HostAddressNeedsUpdating())
        {
            return(_lastHostAddress);
        }

        _logger.LogInformation("Refreshing hosts IP Address ({url}) timeout = {timeout} ms",
                               _providerUrl,
                               _httpTimeoutMs);

        var request  = new HttpRequestMessage(HttpMethod.Get, _providerUrl);
        var response = await _httpService.SendAsync(request, _httpTimeoutMs, stoppingToken);

        var hostIpAddress = (await response.Content.ReadAsStringAsync(stoppingToken)).LowerTrim();

        if (!string.IsNullOrWhiteSpace(hostIpAddress))
        {
            _nextUpdate = _dateTime.Now.AddMinutes(_config.UpdateHostIpIntervalMin);
            return(hostIpAddress);
        }

        _logger.LogWarning("Got empty response, returning old IP Address to be safe");
        return(_lastHostAddress);
    }
Ejemplo n.º 5
0
        public async Task <ActionResult <CommunityResult> > Get(Guid id)
        {
            try
            {
                var result = await _communityService.Get(id);

                return(Ok(result));
            }
            catch (EntityNotFoundException ex)
            {
                _logger.LogWarning(ex, ex.Message);

                return(NotFound("Unable to find Community"));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
            }

            return(BadRequest("Unable to return Community"));
        }
Ejemplo n.º 6
0
        private async Task <ServerHelloResponse> SayHello()
        {
            ServerHelloResponse response = null;

            do
            {
                try
                {
                    response = await client.SayHelloAsync(new ServerHelloRequest { Ip = ipOptions.Ip });
                }
                catch (RpcException e)
                {
                    logger.LogWarning(e, "Could not say hello to server, retrying...");
                }
            } while (response == null);

            return(response);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ContractEventValidationService"/> class.
        /// </summary>
        /// <param name="configReader">Azure config loader.</param>
        /// <param name="options">Configuration options for the validation service.</param>
        /// <param name="logger">Logger Adapater to allow logging within the service.</param>
        public ContractEventValidationService(
            IFeedProcessorConfiguration configReader,
            IOptions <SchemaValidationSettings> options,
            ILoggerAdapter <ContractEventValidationService> logger)
        {
            _options      = options.Value;
            _configReader = configReader;
            _logger       = logger;

            if (_options.SchemaVersion == "11_03")
            {
                _logger.LogInformation($"[{nameof(ContractEventValidationService)}] Loading schema version 11.03.");
                _xmlSchema = ReadSchemaFile(_options.SchemaManifestFilename);
            }
            else
            {
                _logger.LogWarning($"[{nameof(ContractEventValidationService)}] - Active schema version is missing - Schema not loaded");
            }
        }
Ejemplo n.º 8
0
        public void Validate()
        {
            var analyzer = _analyzerResolver.Get();

            var result = new List <ValidationException>();

            foreach (var rule in _rules)
            {
                try
                {
                    var(warnings, exceptions) = rule.Validate(analyzer);
                    result.AddRange(exceptions ?? Enumerable.Empty <ValidationException>());

                    if (warnings is null)
                    {
                        continue;
                    }

                    foreach (var warning in warnings)
                    {
                        _logger.LogWarning(warning);
                    }
                }
                catch (ValidationException e)
                {
                    result.Add(e);
                }
            }

            if (result.Count.Equals(0))
            {
                return;
            }

            if (result.Count.Equals(1))
            {
                throw result.Single();
            }
            else
            {
                throw new AggregateException($"Validation failed for current saga configuration.", result);
            }
        }
Ejemplo n.º 9
0
        public async ValueTask <object> Handle(object message, CancellationToken token = default)
        {
            var result = await HandleInternal(message, token);

            return(result.Success ? result.Message : result.Error);

            async Task <MessageResult> HandleInternal(object message, CancellationToken token)
            {
                _logger.LogDebug("Incoming message {messageName}", message.GetType().Name);
                switch (message)
                {
                case OpenNewTabRequest request:
                    return(await OpenNewTabHandler(request));

                case ResizeTabRequest request:
                    ResizeTabHandler(request);
                    return(MessageResult.Empty);

                case SendInputRequest request:
                    await SendInputRequestHandler(request, token);

                    return(MessageResult.Empty);

                case OpenOutputRequest request:
                    var stream = ConsumeOutput(request, token);
                    return(new MessageResult
                    {
                        Success = true,
                        Message = stream,
                    });

                default:
                    _logger.LogWarning("UnknownMessage {messageName}", message.GetType().Name);
                    return(new MessageResult
                    {
                        Success = false,
                        Error = new UnknownMessageEvent(message.GetType().Name)
                    });
                }
            }
        }
Ejemplo n.º 10
0
        public void AddSteps(ISagaVersion version, IList <ISagaStepConfiguration> configurations)
        {
            if (version is null)
            {
                throw new ArgumentNullException(nameof(version));
            }

            if (configurations is null)
            {
                throw new ArgumentNullException(nameof(configurations));
            }

            if (_steps.ContainsKey(version))
            {
                _steps[version] = configurations;

                _logger.LogWarning($"Version {version} was already added. The given configuration is now replaced.");
            }
            else
            {
                _steps.Add(version, configurations);
            }
        }
        /// <inheritdoc/>
        public async Task <bool> ValidateContractStatusAsync(string parentContractStatus, string contractStatus, string amendmentType)
        {
            _logger.LogInformation($"[{nameof(ValidateContractStatusAsync)}] Attempting to validate contract status '{parentContractStatus}/{contractStatus}/{amendmentType}'.");

            IList <ValidationServiceConfigurationStatuses> statusTernaries = await GetContractStatusesAsync();

            if (statusTernaries.Any(
                    p => p.ParentContractStatus.ToLower() == parentContractStatus.ToLower() &&
                    p.ContractStatus.ToLower() == contractStatus.ToLower() &&
                    p.AmendmentType.ToLower() == amendmentType.ToLower()))
            {
                _logger.LogInformation($"[{nameof(ValidateContractStatusAsync)}] Contract status '{parentContractStatus}/{contractStatus}/{amendmentType}' is valid..");
                return(true);
            }

            _logger.LogWarning($"[{nameof(ValidateContractStatusAsync)}] Contract status '{parentContractStatus}/{contractStatus}/{amendmentType}' is NOT valid.");
            return(false);
        }
Ejemplo n.º 12
0
        private async Task <ContractProcessResultType> GetProcessedResultType(XmlElement feedItem, XmlNamespaceManager ns, ContractEvent evt)
        {
            var contractStatus = feedItem.GetValue <string>("c:contractStatus/c:status", ns);
            var parentStatus   = feedItem.GetValue <string>("c:contractStatus/c:parentStatus", ns);

            var amendmentType = feedItem.GetValue("c:amendmentType", ns, true, "None");
            var fundingType   = feedItem.GetValue <string>("c:fundingType/c:fundingTypeCode", ns);

            var resultCode = !await _validationService.ValidateContractStatusAsync(parentStatus, contractStatus, amendmentType)
                                ? ContractProcessResultType.StatusValidationFailed
                                : !await _validationService.ValidateFundingTypeAsync(fundingType)
                                    ? ContractProcessResultType.FundingTypeValidationFailed
                                    : ContractProcessResultType.Successful;

            if (resultCode != ContractProcessResultType.Successful)
            {
                string msg = $"Contract event for Contract [{evt.ContractNumber}] Version [{evt.ContractVersion}]";
                msg += resultCode switch
                {
                    ContractProcessResultType.StatusValidationFailed => $" with parent status [{parentStatus}], status [{contractStatus}], and amendment type [{amendmentType}] has been ignored.",
                    ContractProcessResultType.FundingTypeValidationFailed => $" with funding type [{fundingType}] has been ignored.",
                    _ => throw new NotImplementedException(),
                };

                _loggerAdapter.LogWarning(msg);
                await _auditService.TrySendAuditAsync(new Audit.Api.Client.Models.Audit()
                {
                    Action   = Audit.Api.Client.Enumerations.ActionType.ContractFeedEventFilteredOut,
                    Message  = msg,
                    Severity = Audit.Api.Client.Enumerations.SeverityLevel.Information,
                    Ukprn    = evt.UKPRN,
                    User     = _auditApiUser
                });
            }

            return(resultCode);
        }