예제 #1
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);
        }
예제 #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));
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ContractDocumentService"/> class.
 /// </summary>
 /// <param name="configuration">Configuration options.</param>
 /// <param name="logger">The Logger.</param>
 /// <param name="blobContainerClient">The blob container client for blob maintenance.</param>
 public ContractDocumentService(BlobContainerClient blobContainerClient, ILoggerAdapter <IContractDocumentService> logger)
 {
     _logger = logger;
     _logger.LogInformation($"[{nameof(ContractDocumentService)}] instantiating...");
     _blobContainerClient = blobContainerClient;
     _logger.LogInformation($"[{nameof(ContractDocumentService)}] instantiated.");
 }
예제 #4
0
        /// <inheritdoc/>
        public async Task <IList <ContractProcessResult> > DeserializeAsync(string xml)
        {
            _loggerAdapter.LogInformation($"[{nameof(Deserializer_v1103)}.{nameof(DeserializeAsync)}] - Called to deserilise xml string.");

            var contractList = new List <ContractProcessResult>();

            // Ensure xml is valid.
            var document = _validationService.ValidateXmlWithSchema(xml);

            var ns = new XmlNamespaceManager(new NameTable());

            ns.AddNamespace("c", _contractEvent_Namespace);

            // The content element may be in either case.
            var details       = (document["content"] ?? document["Content"])["contract"];
            var feedContracts = details.SelectNodesIgnoreCase("c:contracts/c:contract", ns);

            foreach (XmlElement feedContract in feedContracts)
            {
                var evt = DeserializeContractEvent(feedContract, ns);

                contractList.Add(new ContractProcessResult
                {
                    Result        = await GetProcessedResultType(feedContract, ns, evt),
                    ContractEvent = evt,
                    ContractXml   = document
                });
            }

            _loggerAdapter.LogInformation($"[{nameof(Deserializer_v1103)}.{nameof(DeserializeAsync)}] - Deserialistion completed.");
            return(contractList);
        }
예제 #5
0
        public async Task <bool> GetMaintainableFlag(string propertyReference)
        {
            bool maintainableFlag = false;

            _logger.LogInformation($"Getting the maintainable flag from UHT for {propertyReference}");
            try
            {
                using (var command = _context.Database.GetDbConnection().CreateCommand())
                {
                    _context.Database.OpenConnection();
                    command.CommandText = @"SELECT 
                    [no_maint]
                    FROM [property]
                    WHERE prop_ref ='" + propertyReference + "'";
                    command.CommandType = CommandType.Text;
                    using (var reader = await command.ExecuteReaderAsync())
                    {
                        if (reader != null & reader.HasRows)
                        {
                            maintainableFlag = reader.GetBoolean(0);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
            }
            return(!maintainableFlag);
        }
예제 #6
0
        public Task StartSimulationAsync(PlantSimulationOptions options, CancellationToken cancellationToken)
        {
            logger.LogInformation("Starting simulator from runtime broker");

            options = (PlantSimulationOptions)FluidsPlantOptions.CreateOptions();

            // Set the random seed from the options
            RangeExtensions.Random = new Random(options.Simulation.RandomSeed);

            // Set the options service options to the received options
            optionsService.Options = options;

            // Linked cancellation token source so that the simulation can be cancelled
            cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);

            // Instantiate the simulation instance with the dependency injection service container
            Simulation = provider.ResolvePlantSimulatorConstructor();

            // Add event subscribers to the OnTick event
            Simulation.OnTick += eventHandler.OnSimulationTick;

            // Start the simulation if it was instantiated correctly through dependency injection
            try
            {
                runningSimulation = Simulation.StartAsync(cancellationTokenSource.Token);
            }
            catch (NullReferenceException e)
            {
                throw new NullReferenceException("The simulation could not be constructed by the service provider", e);
            }


            return(Task.CompletedTask);
        }
예제 #7
0
        /// <inheritdoc/>
        public async Task <ContractReminders> GetOverdueContracts()
        {
            string querystring = CreateQueryString(_dataApiConfiguration.ContractReminderEndpoint);

            _logger.LogInformation($"Requesting a list of contracts with overdue reminders with querystring {querystring}.");
            return(await Get <ContractReminders>(querystring));
        }
예제 #8
0
        /// <summary>
        /// Adds a page to the pdf detailing that the contract was digitally signed.
        /// </summary>
        /// <param name="pdf">The PDF to add the page to.</param>
        /// <param name="contractRefernce">The contract reference.</param>
        /// <param name="signer">Who signed the contract.</param>
        /// <param name="signedOn">When the contract was signed.</param>
        /// <param name="manuallyApproved">Flag indicating if the contract was manually approved.</param>
        /// <param name="fundingType">the contract funding type.</param>
        /// <param name="principalId">The ID of the current user.</param>
        /// <returns>The PDF with signed page.</returns>
        public byte[] AddSignedDocumentPage(byte[] pdf, string contractRefernce, string signer, DateTime signedOn, bool manuallyApproved, ContractFundingType fundingType, string principalId = null)
        {
            _logger.LogInformation($"[{nameof(AddSignedDocumentPage)}] Adding signed document page to {contractRefernce}.");

            using (var inputStream = new MemoryStream(pdf))
            {
                using (var doc = new Document(inputStream))
                {
                    var newPage        = doc.Pages.Insert(1);
                    var cursorLocation = 0d;

                    var imageHeight = AddImage(newPage, $"{AsposeLicenceManagement.EmbededResourcesNamespace}.Logo.png", 170, 105);

                    var top = CreateTextBox(newPage);
                    cursorLocation = imageHeight + 100;
                    top.Top        = cursorLocation;

                    var contractType = "contract";

                    if (fundingType == ContractFundingType.Levy)
                    {
                        contractType = "agreement";
                    }

                    top.Paragraphs.Add(CreateTitle($"Signed {contractType} document"));

                    if (manuallyApproved)
                    {
                        top.Paragraphs.Add(CreateParagraph($"This {contractType} has been signed by the authorised signatory for the {OrganisationName}, acting on behalf of the Secretary of State."));
                    }
                    else
                    {
                        top.Paragraphs.Add(CreateParagraph($"This {contractType} has been signed by the authorised signatory for the {OrganisationName}, acting on behalf of the Secretary of State, and has been digitally signed by all parties."));
                    }

                    var bottom = CreateTextBox(newPage);
                    cursorLocation += top.Height + 200;
                    bottom.Top      = cursorLocation;
                    bottom.Paragraphs.Add(CreateParagraph($"Document reference: {contractRefernce}"));
                    bottom.Paragraphs.Add(CreateParagraph($"Signed by {signer} on {signedOn.ToDateDisplay()} as the provider's authorised signatory"));
                    if (!string.IsNullOrEmpty(principalId))
                    {
                        bottom.Paragraphs.Add(CreateParagraph($"User ID: {principalId}"));
                    }

                    using (var outputStream = new MemoryStream())
                    {
                        doc.ConvertToPdfA();

                        EnsureLandscapePagesAreMarkedCorrectly(doc);
                        doc.Save(outputStream, SaveFormat.Pdf);
                        _logger.LogInformation($"[{nameof(AddSignedDocumentPage)}] Added signed document page to {contractRefernce}.");
                        return(outputStream.ToArray());
                    }
                }
            }
        }
        public async Task <IEnumerable <Inspection> > GetInspection(string propertyId)
        {
            _logger.LogInformation($"Calling GetInspections() with {propertyId}");
            var response = await _api.GetInspections(propertyId);

            var responseInspections = response.Data;

            return(responseInspections);
        }
        public Task StartAsync(CancellationToken cancellationToken)
        {
            logger.LogInformation("Host is starting");

            lifetime.ApplicationStarted.Register(() => runtime.StartAsync(cancellationToken));
            lifetime.ApplicationStopping.Register(() => runtime.StopAsync(cancellationToken));

            return(Task.CompletedTask);
        }
예제 #11
0
        private void TwitchClientConnected(object sender, OnConnectedArgs onConnectedArgs)
        {
            _logger.LogInformation($"{nameof(TwitchChatClient)} connected");
            _twitchClient.OnConnected -= TwitchClientConnected;

            _isReady = true;
            _connectionCompletionTask.SetResult(true);
            _disconnectionCompletionTask = new TaskCompletionSource <bool>();
        }
예제 #12
0
        public async Task <IActionResult> Post([FromBody] SecretDto secret)
        {
            _loggerAdapter.LogInformation("secret method call started");
            var secretCommand = _mapper.Map <CreateSecretCommand>(secret);
            var result        = await _mediator.Send(secretCommand);

            _loggerAdapter.LogInformation("secret method call ended");
            return(new OkObjectResult(result));
        }
예제 #13
0
 protected override async Task ExecuteAsync(CancellationToken stoppingToken)
 {
     _logger.LogInformation("CleanArchitecture.Worker running at: {time}", nameof(Worker), DateTimeOffset.Now);
     while (!stoppingToken.IsCancellationRequested)
     {
         _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
         await Task.Delay(_settings.DelayMilliseconds, stoppingToken); // TODO: Move delay to appSettings
     }
     _logger.LogInformation("CleanArchitecture.Worker stopping at: {time}", nameof(Worker), DateTimeOffset.Now);
 }
예제 #14
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            logger.LogInformation("Sending Hello Message to Server");

            var response = await SayHello();

            Id = response.Id;

            logger.LogInformation("Received Id " + Id);
        }
예제 #15
0
 protected override async Task ExecuteAsync(CancellationToken stoppingToken)
 {
     _logger.LogInformation("CleanArchitecture.Worker service starting at: {time}", DateTimeOffset.Now);
     while (!stoppingToken.IsCancellationRequested)
     {
         await _entryPointService.ExecuteAsync();
         await Task.Delay(_settings.DelayMilliseconds, stoppingToken);
     }
     _logger.LogInformation("CleanArchitecture.Worker service stopping at: {time}", DateTimeOffset.Now);
 }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("UpdateService.Worker service starting at: {time}", DateTimeOffset.Now);
            while (!stoppingToken.IsCancellationRequested)
            {
                await _entryPointService.ExecuteAsync();

                await Task.Delay(1000, stoppingToken); // TODO: Move delay to appSettings
            }
            _logger.LogInformation("UpdateService.Worker service stopping at: {time}", DateTimeOffset.Now);
        }
        /// <inheritdoc/>
        public async Task UpsertOriginalContractXmlAsync(DataModels.Contract contract, ContractRequest request)
        {
            _logger.LogInformation($"[{nameof(UpsertOriginalContractXmlAsync)}] called with contract number: {request.ContractNumber} and version {request.ContractVersion}.");
            if (contract.ContractData is null)
            {
                contract.ContractData    = new DataModels.ContractData();
                contract.ContractData.Id = contract.Id;
            }

            contract.ContractData.OriginalContractXml = await GetDocumentContentAsync(request);
        }
예제 #18
0
        /// <inheritdoc />
        public async Task UploadAsync(string filename, byte[] contents, bool overwrite = true)
        {
            _loggerAdapter.LogInformation($"Uploading file [{filename}] to storage container [{_blobContainerClient.AccountName}/{_blobContainerClient.Name}].");
            var blob = _blobContainerClient.GetBlobClient(filename);

            using var ms = new MemoryStream(contents);

            await blob.UploadAsync(ms, overwrite);

            _loggerAdapter.LogInformation($"Upload of [{filename}] sucessful.");
        }
예제 #19
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("QuartzHostedService Start");

            await RunAsync(stoppingToken);

            await Task.Delay(-1, stoppingToken);

            await KillAsync(stoppingToken);

            _logger.LogInformation("QuartzHostedService Shutdown");
        }
        public async Task <ActionResult <Contract> > Get(int id)
        {
            _logger.LogInformation($"Get by unique identifier called with id: {id}.");
            var contract = await _contractService.GetAsync(id);

            if (contract is null)
            {
                return(NotFound());
            }

            return(contract);
        }
예제 #21
0
        public async Task <List <GenericLookupResult> > GetAllAbilities()
        {
            List <tlkpAbility> abilities = await _pokedexRepository.GetAllAbilities();

            _logger.LogInformation(string.Format(Constants.InformationalMessageMappingWithCount, abilities.Count, Constants.Ability, Results));

            return(abilities.Select(a => new GenericLookupResult
            {
                Id = a.Id,
                Name = a.Name
            }).ToList());
        }
예제 #22
0
        public async Task <IEnumerable <Inspection> > GetInspection(string propertyId)
        {
            _logger.LogInformation($"Calling GetInspection() with {propertyId}");
            var lInspection = await _asbestosService.GetInspection(propertyId);

            if (lInspection.Any() == false)
            {
                _logger.LogError($"No inspections returned for {propertyId}");
                throw new MissingInspectionException();
            }
            return(lInspection);
        }
예제 #23
0
        public ActionResult InsertOrUpdateEntry()
        {
            var entry  = _jwtPayload.GetPayload("JWTSignedPayload").ToObject <LadderEntry>();
            var result = _ladderService.Upsert(entry);

            if (result == null)
            {
                _logger.LogInformation("Returning bad request for entry. Maybe malformed request?");
                return(BadRequest());
            }

            _logger.LogInformation("Successfully added or updated entry");
            return(Ok(result));
        }
예제 #24
0
        /// <inheritdoc/>
        public async Task ProcessMessage(ContractApprovedMessage message)
        {
            if (message is null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            _logger.LogInformation($"Sending approved contract notification for {message.ContractNumber}.");

            await Post(_configuration.ApiContractApproverEndpoint, message);

            try
            {
                await _audit.AuditAsync(new Audit.Api.Client.Models.Audit()
                {
                    Action   = ActionType.ContractApprovedMessageSentToFCS,
                    Severity = 0,
                    User     = ContractApproverUser,
                    Ukprn    = message.Ukprn,
                    Message  = $"Notified FCS of approved contract [{message.ContractNumber}] Version [{message.ContractVersionNumber}]."
                });
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Error when attempting to create an audit entry.");
            }
        }
예제 #25
0
파일: WelcomeJob.cs 프로젝트: aviezzi/arale
        public async Task Execute(IJobExecutionContext context)
        {
            _logger.LogInformation("Start WelcomeJob");

            try
            {
                await _client.Notify(
                    $@"Hi <!channel>. I'm {_options.ApplicationName}, I am your shifts managing assistant!");
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"{e.Message}");
            }

            _logger.LogInformation("WelcomeJob Completed");
        }
예제 #26
0
        public async Task ExecuteAsync()
        {
            _logger.LogInformation("{service} running at: {time}", nameof(EntryPointService), DateTimeOffset.Now);
            try
            {
                // EF Requires a scope so we are creating one per execution here
                using var scope = _serviceScopeFactoryLocator.CreateScope();
                var repository =
                    scope.ServiceProvider
                    .GetService <IRepository>();

                // read from the queue
                string message = await _queueReceiver.GetMessageFromQueue(_settings.ReceivingQueueName);

                if (String.IsNullOrEmpty(message))
                {
                    return;
                }

                // check 1 URL in the message
                var statusHistory = await _urlStatusChecker.CheckUrlAsync(message, "");

                // record HTTP status / response time / maybe existence of keyword in database
                repository.Add(statusHistory);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"{nameof(EntryPointService)}.{nameof(ExecuteAsync)} threw an exception.");
                // TODO: Decide if you want to re-throw which will crash the worker service
                //throw;
            }
        }
예제 #27
0
        public async Task <IList <CustomerDto> > GetAllCustomers()
        {
            _logger.LogInformation("Method GetAllCustomers Invoked.");
            try
            {
                var result = await _getAllCustomersQuery.Get();

                var mappedResult = _mapperAdapter.Map <IList <CustomerDto> >(result);
                return(mappedResult);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Method GetAllCustomers failed.");
                throw;
            }
        }
예제 #28
0
        private CommandUsage AttemptToRunCommand(CommandReceivedEventArgs e,
                                                 IBotCommand botCommand, IChatClient chatClient1, IList <string> args)
        {
            try
            {
                _logger.LogInformation($"{e.ChatUser.DisplayName} is running the {botCommand.GetType().Name} command.");

                if (e.ChatUser.CanRunCommand(botCommand))
                {
                    if (args.Any())
                    {
                        e.Arguments.Clear();
                        foreach (string arg in args)
                        {
                            e.Arguments.Add(arg);
                        }
                    }
                    return(botCommand.Process(chatClient1, e));
                }

                chatClient1.SendMessage(
                    $"Sorry, {e.ChatUser.DisplayName}! You don't have permission to use the !{e.CommandWord} command.");
            }
            catch (Exception exception)
            {
                _logger.LogError(exception, "Failed to run a command.");
            }

            return(new CommandUsage(e.ChatUser.DisplayName, DateTimeOffset.UtcNow, botCommand));
        }
예제 #29
0
 public xmbCheckAvailability BuildXmbCheckAvailabilityRequest(string workOrderReference, string sessionId, DrsOrder drsOrder, DateTime startPeriod, DateTime endPeriod)
 {
     _logger.LogInformation($"Building the xmbCheckAvailability request for {workOrderReference}");
     try
     {
         var xmbCheckAvailability = new xmbCheckAvailability
         {
             theOrder             = buildTheOrderForRequest(workOrderReference, drsOrder),
             sessionId            = sessionId,
             periodBegin          = startPeriod,
             periodEnd            = endPeriod,
             periodBeginSpecified = true,
             periodEndSpecified   = true,
             canSelectOtherOrders = false,
             checkAvailType       = checkAvailTypeType.standard,
             onlyBestSlots        = onlyBestSlotsValue.fullPeriod
         };
         return(xmbCheckAvailability);
     }
     catch (Exception ex)
     {
         _logger.LogError(ex.Message);
     }
     return(null);
 }
예제 #30
0
        public async Task <IActionResult> Index(PokemonFormViewModel pokemonFormViewModel)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    await _pokedexAppLogic.AddPokemon(pokemonFormViewModel);

                    return(View(Constants.Success, new SuccessViewModel()
                    {
                        ActionName = "addition"
                    }));
                }
                else
                {
                    _logger.LogInformation(Constants.InvalidRequest);

                    return(await Index());
                }
            }
            catch (Exception ex)
            {
                return(Error(ex));
            }
        }