public async Task <Guid> AddAmountToBeneficiaryBalanceAsync(WireTransfer wireTransfer) { var transactionId = await _transactionApiConfiguration.Url .AppendPathSegment(_transactionApiConfiguration.CreateTransactionPathSegment) .ConfigureRequest(settings => { settings.BeforeCall = call => { _logging.Information(call.Request.RequestUri); var transactionIdResponse = GetTransactionId(wireTransfer); if (transactionIdResponse != null) { throw new DuplicateException( "Cannot create another transaction for the same wire transfer", DuplicateRuleValidationEnumeration.ERROR_WIRE_TRANSFER_TRANSACTION_DUPLICATED); } }; }) .PostJsonAsync(new { IdContaBancaria = wireTransfer.BeneficiaryBankAccount.BankAccountLegacyId.Value, TipoOperacao = WireTransferTypeOperation, TipoLancamento = WireTransferTypeTransaction, Descricao = $"Recebeu de {wireTransfer.SenderBankAccount.BankAccountHolder.HolderName}", Valor = wireTransfer.Amount.Value, IdCategoria = WireTransferCategoryId, DataTransacao = DateTime.Now, UniqueId = wireTransfer.ProtocolTrackable.ProtocolNumber }).ReceiveJson <TransactionIdResponse>(); return(transactionId.TransactionId); }
public async Task <decimal> GetInterestRateAsync() { try { var response = await _interestRateApiQueryConfig.Host .AppendPathSegment(_interestRateApiQueryConfig.Path) .ConfigureRequest(setup => { setup.JsonSerializer = new NewtonsoftJsonSerializer(new JsonApiSerializerSettings()); setup.BeforeCall = call => { _logging.Information(new { details = "calling InterestRateApiQuery", request = new { requestUri = call.Request.RequestUri, boby = call.Request.Content } }); }; }) .GetAsync() .ReceiveJson <InterestRateResponse>() ?? new InterestRateResponse(); return(response.InterestRate); } catch (Exception e) { _logging.Error(new { details = "get interest rate", exception = new { inner = e.InnerException, message = e.Message } }); throw; } }
private async void PublishWireTransferOnTopic(PublishWireTransferOnTopicNotification notification, CancellationToken cancellationToken) { using var producer = new ProducerBuilder <string, string>(GetProducerConfig()).Build(); var messageId = Guid.NewGuid().ToString(); await producer.ProduceAsync( _publishTopicSettings.TopicName, new Message <string, string> { Key = messageId, Value = JsonConvert.SerializeObject(notification.WireTransfer, new JsonApiSerializerSettings()) }, cancellationToken).ContinueWith(task => { if (task.IsFaulted) { _logging.Error(task.Exception); } if (task.IsCompletedSuccessfully) { _logging.Information(task); } }, cancellationToken); }
public FinancialContract Get() { var financial = new FinancialContract { Id = Guid.NewGuid(), InterestRate = Financial.InterestRate }; _logging.Information(financial); return(financial); }
private static string?GetVsTools() { //We already check in CreateLoader but makes the compiler happy if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return(null); } ManagementObjectCollection mcCollection; try { using ManagementClass mc = new ManagementClass("MSFT_VSInstance"); mcCollection = mc.GetInstances(); } catch (Exception e) { Logger.Error(e); return(null); } //We want to buildtools if they have it install, we'll use VS installs if needed ManagementBaseObject?vsInstall = null; foreach (var result in mcCollection) { vsInstall ??= result; if ((string?)result?["ProductId"] == "Microsoft.VisualStudio.Product.BuildTools") { Logger.Debug("Found VS Build Tools, using that install"); return((string?)result["InstallLocation"]); } } var installLocation = (string?)vsInstall?["InstallLocation"]; if (string.IsNullOrWhiteSpace(installLocation)) { Logger.Error("Unable to find any VS install or VS Build Tools"); return(null); } Logger.Information("Found VS install ({0}), using that", vsInstall?["Name"]); return(installLocation); }
/// <summary> /// Checks that the <see cref="ReleaseEntry"/> can be used /// </summary> public static bool CheckReleaseEntry(this ReleaseEntry releaseEntry, SemanticVersion applicationVersion, bool successfullyDownloaded) { Logger.Information("Checking {0}", releaseEntry.Filename); if (successfullyDownloaded && releaseEntry.IsValidReleaseEntry(applicationVersion, true)) { return(true); } Logger.Error("Checking file {0} failed after downloading, going to delete it to be safe", releaseEntry.Filename); try { File.Delete(releaseEntry.FileLocation); } catch (Exception e) { Logger.Error(e); } return(false); }
/// <summary> /// Get details beneficiary from Checking Account /// </summary> /// <param name="beneficiaryAccountHolder"></param> /// <param name="beneficiaryBankAccountDetails"></param> /// <returns></returns> public async Task <BankAccount> AccountUniquenessChecker( BankAccountHolder beneficiaryAccountHolder, BankAccountDetails beneficiaryBankAccountDetails) { var json = await _checkingAccountApiConfiguration.Url .AppendPathSegment(_checkingAccountApiConfiguration.GetDetailsBeneficiaryAccountPathSegment) .ConfigureRequest(settings => { settings.BeforeCall = call => { _logging.Information(call.Request.RequestUri); }; }) .SetQueryParam("filter[person.document]", beneficiaryAccountHolder.HolderDocument.Value) .SetQueryParam("filter[number]", beneficiaryBankAccountDetails.GetAccountWithoutDigit()) .SetQueryParam("filter[digit]", beneficiaryBankAccountDetails.Digit) .SetQueryParam("filter[branch]", beneficiaryBankAccountDetails.Branch) .GetStringAsync(); var response = (JsonConvert.DeserializeObject <List <BeneficiaryBankAccountDetails> >(json, new JsonApiSerializerSettings()) ?? throw new JsonException("Error to build https://jsonapi.org/ specification")).FirstOrDefault(); if (response != null) { var account = new BankAccountBuilder() .WithBankAccountId(response.Id) .WithBankAccountLegacyId(response.LegacyId) .WithBankAccountHolder(beneficiaryAccountHolder.HolderName, beneficiaryAccountHolder.HolderDocument.Value) .WithBankAccountDetails(beneficiaryBankAccountDetails.Account, beneficiaryBankAccountDetails.Branch, beneficiaryBankAccountDetails.Number) .IsBlocked(response.Blocked) .IsCanceled(response.Canceled) .Build(); return(account); } return(new BankAccountBuilder().Build()); }
public async Task <FinancialContract> Handle(CalculateInterestCommand request, CancellationToken cancellationToken) { try { _logging.Information(new { details = "calculate interest", entity = request }); var financial = new Financial(request.Amount, request.Months); var interestResult = await financial.CalculateInterest(_interestRateQueryApi); var currencyType = request.CurrencyDisplay ?? CurrencyDisplay.PtBr; return(new FinancialContract { Id = financial.Id, Amount = financial.Amount, Months = financial.Months, SimpleInterest = interestResult, ValuesInCurrency = new DisplayValuesContract { Type = currencyType.ToString(), AmountCurrency = financial.Amount.FormatToCurrency(currencyType), SimpleInterestCurrency = interestResult.FormatToCurrency(currencyType) } }); } catch (Exception e) { _logging.Error(new { details = "calculate interest", entity = request, exception = new { inner = e.InnerException, message = e.Message } }); throw; } }
public bool CreateDeltaPackage( ApplicationMetadata applicationMetadata, string newVersionLocation, SemanticVersion newVersion, string baseVersionLocation, SemanticVersion oldVersion, string outputFolder, string deltaUpdateLocation, OSPlatform?intendedOs = null, Action <double>?progress = null) { if (!Directory.Exists(newVersionLocation) || !Directory.Exists(baseVersionLocation)) { _logger.Error("One of the folders don't exist, can't create delta update...."); return(false); } _logger.Debug("Creating delta file"); var zipArchive = CreateZipArchive(deltaUpdateLocation); var tempFolder = new TemporaryFolder(applicationMetadata.TempFolder); void Cleanup() { lock (zipArchive) { zipArchive.Dispose(); } tempFolder.Dispose(); progress?.Invoke(1); } //Get all the files that are in the new version (Removing the Path so we only have the relative path of the file) var newVersionFiles = Directory.EnumerateFiles(newVersionLocation, "*", SearchOption.AllDirectories) .RemovePath(newVersionLocation).ToArray(); //and get the files from the old version var baseVersionFiles = Directory.EnumerateFiles(baseVersionLocation, "*", SearchOption.AllDirectories) .RemovePath(baseVersionLocation).ToArray(); //Find any files that are in both version and process them based on if they had any changes var sameFiles = newVersionFiles.Where(x => baseVersionFiles.Contains(x)).ToArray(); var newFiles = newVersionFiles.Where(x => !sameFiles.Contains(x)).ToArray(); var progressReport = new ProgressReport(newFiles.Length + sameFiles.Length, progress); var deltaFiles = new List <string>(sameFiles.Length); //First process any files that didn't change, don't even count them in the progress as it will be quick af _logger.Information("Processing files that are in both versions"); foreach (var maybeDeltaFile in sameFiles) { _logger.Debug("Processing possible delta file {0}", maybeDeltaFile); var newFileLocation = Path.Combine(newVersionLocation, maybeDeltaFile); /*See if we got a delta file, if so then store it for * processing after files that haven't changed*/ if (IsDeltaFile(Path.Combine(baseVersionLocation, maybeDeltaFile), newFileLocation)) { deltaFiles.Add(maybeDeltaFile); continue; } //Add a pointer to the file that hasn't changed _logger.Debug("{0} hasn't changed, processing as unchanged file", maybeDeltaFile); using var fileStream = File.OpenRead(newFileLocation); if (AddSameFile(zipArchive, maybeDeltaFile, SHA256Util.CreateSHA256Hash(fileStream))) { progressReport.ProcessedFile(); continue; } _logger.Warning("We wasn't able to add {0} as a file that was unchanged, adding as a \"new\" file", maybeDeltaFile); //We wasn't able to add the file as a pointer, try to add it as a new file if (!AddNewFile(zipArchive, fileStream, maybeDeltaFile)) { //Hard bail if we can't even do that _logger.Error("Wasn't able to process {0} as a new file as well, bailing", maybeDeltaFile); Cleanup(); return(false); } progressReport.ProcessedFile(); } //TODO: add "moved files" //Now process files that was added into the new version _logger.Information("Processing files that only exist in the new version"); foreach (var newFile in newFiles) { _logger.Debug("Processing new file {0}", newFile); //Process new file using var fileStream = File.OpenRead(Path.Combine(newVersionLocation, newFile)); if (AddNewFile(zipArchive, fileStream, newFile)) { progressReport.ProcessedFile(); continue; } //if we can't add it then hard fail, can't do anything to save this _logger.Error("Wasn't able to process new file, bailing"); Cleanup(); return(false); } //Now process files that changed var result = Parallel.ForEach(deltaFiles, (deltaFile, state) => { var deltaFileLocation = Path.Combine(newVersionLocation, deltaFile); _logger.Debug("Processing changed file {0}", deltaFile); //Try to add the file as a delta file if (AddDeltaFile(tempFolder, zipArchive, Path.Combine(baseVersionLocation, deltaFile), deltaFileLocation, intendedOs, (pro) => progressReport.PartialProcessedFile(pro))) { progressReport.ProcessedFile(); return; } //If we can't make the file as a delta file try to create it as a "new" file _logger.Warning("Wasn't able to make delta file, adding file as \"new\" file"); using var fileStream = File.OpenRead(Path.Combine(newVersionLocation, deltaFileLocation)); if (AddNewFile(zipArchive, fileStream, deltaFile)) { progressReport.ProcessedFile(); return; } //Hard bail if we can't even do that _logger.Error("Wasn't able to process file as a new file, bailing"); Cleanup(); state.Break(); }); //This will return false if something failed if (!result.IsCompleted) { return(false); } if (ShouldMakeLoader && !AddLoaderFile( tempFolder, applicationMetadata, zipArchive, newVersion, newVersionLocation, intendedOs, oldVersion, outputFolder)) { _logger.Error("Wasn't able to create loader for this application"); Cleanup(); return(false); } progressReport.ProcessedFile(); //We have created the delta file if we get here, do cleanup and then report as success! _logger.Information("We are done with creating the delta file, cleaning up"); Cleanup(); return(true); }