public async Task <bool> UpdateAsync(Rate rate) { try { if (rate == null) { throw new ArgumentNullException(); } RateEntity entity = await _context.Rates .FindAsync(rate.RateId) .ConfigureAwait(false); if (entity != null) { _mapper.Map(rate, entity); await _context.SaveChangesAsync().ConfigureAwait(false); return(true); } } catch (Exception e) { _context.DetachAll(); _logger.LogError(e, "Exception: {e} // Internal Error while updating Rate: {rate}", e.Message, JsonSerializer.Serialize(rate)); } return(false); }
public async Task <Rate> AddAsync(AddRateRequest rate) { try { if (rate == null) { throw new ArgumentNullException(); } RateEntity entity = _mapper.Map <RateEntity>(rate); var addResponse = await _context.Rates.AddAsync(entity).ConfigureAwait(false); if (addResponse.State.Equals(EntityState.Added)) { bool created = await _context.SaveChangesAsync().ConfigureAwait(false) > 0; return(created ? _mapper.Map <Rate>(addResponse.Entity) : null); } } catch (Exception e) { _context.DetachAll(); _logger.LogError(e, "Exception: {e} // Internal Error while adding new Rate: {rate}", e.Message, JsonSerializer.Serialize(rate)); } return(null); }
private async Task <RateEntity> LoadRateAsync(string currency) { RestClient client = new RestClient { BaseUrl = new Uri("http://finance.yahoo.com") }; string resource = string.Format("/d/quotes.csv?e=.csv&f=sl1d1t1&s={0}{1}=X", currency, "INR"); var request = new RestRequest(resource, Method.GET); var cancellationTokenSource = new CancellationTokenSource(); var restResponse = await client.ExecuteTaskAsync(request, cancellationTokenSource.Token); var response = restResponse.Content; string[] values = Regex.Split(response, ","); decimal rate = System.Convert.ToDecimal(values[1]); decimal conversionRate = decimal.Parse(values[1], CultureInfo.InvariantCulture); var rateResp = new RateEntity { SourceCurrency = currency, ConversionRate = conversionRate, }; return(rateResp); }
public static RateApplication Map(RateEntity rate) => new RateApplication { CurrencyFrom = rate.CurrencyFrom, CurrencyTo = rate.CurrencyTo, RateDifference = rate.Rate };
private RateRm GetReadModelEntity(RateEntity rate, Rate rateDefinition, int order) { var timeAdded = DateTimeOffset.Parse(rate.TimeKey); // calculate changes var oneDayChange = GetRateChange(rate.Ticker, timeAdded.AddDays(-1), rate.Value); var oneWeekChange = GetRateChange(rate.Ticker, timeAdded.AddDays(-7), rate.Value); var oneMonthChange = GetRateChange(rate.Ticker, timeAdded.AddMonths(-1), rate.Value); var threeMonthChange = GetRateChange(rate.Ticker, timeAdded.AddMonths(-3), rate.Value); var sixMonthChange = GetRateChange(rate.Ticker, timeAdded.AddMonths(-6), rate.Value); var oneYearChange = GetRateChange(rate.Ticker, timeAdded.AddYears(-1), rate.Value); var twoYearChange = GetRateChange(rate.Ticker, timeAdded.AddYears(-2), rate.Value); var fiveYearChange = GetRateChange(rate.Ticker, timeAdded.AddYears(-5), rate.Value); // return the read model entry return(new RateRm( ticker: rate.Ticker, name: rateDefinition.Name, href: rateDefinition.Href, value: rate.Value, order: order, change1Day: oneDayChange, change1Week: oneWeekChange, change1Month: oneMonthChange, change3Months: threeMonthChange, change6Months: sixMonthChange, change1Year: oneYearChange, change2Year: twoYearChange, change5Year: fiveYearChange )); }
public void GetCurrentRateTest() { var location = Seed.SeedData().LocationEntity; const int occupants = 1; const int price = 200; const string description = "Test"; var paymentDate = DateTime.Parse("01.01.2020"); var startDate = DateTime.Parse("01.01.2020"); var endDate = DateTime.Parse("01.02.2020"); var expected = new RateEntity { StartDate = startDate, EndDate = endDate, Description = description, Price = price, IsArchive = true }; using (var scope = _container.BeginLifetimeScope()) { var rateService = scope.Resolve <IRateService>(); var rate = rateService.AddRate(location, description, price, startDate, endDate); var actual = rateService.GetCurrentRate(occupants, location, paymentDate); Assert.AreEqual(expected.Price, actual); } }
public void ChangeRatePriceTest() { var location = Seed.SeedData().LocationEntity; const int price = 200; const string description = "Test"; const decimal newPrice = 300; var starDate = DateTime.Parse("01.01.2020"); var endDate = DateTime.Parse("01.02.2020"); var expected = new RateEntity { StartDate = starDate, EndDate = endDate, Description = description, Price = newPrice, IsArchive = true }; using (var scope = _container.BeginLifetimeScope()) { var rateService = scope.Resolve <IRateService>(); var rate = rateService.AddRate(location, description, price, starDate, endDate); var actual = rateService.ChangeRatePrice(rate, newPrice, endDate); Assert.AreEqual(expected.Price, actual.Price); Assert.AreEqual(expected.IsArchive, rate.IsArchive); } }
public async Task <bool> DeleteAsync(int rateId) { try { RateEntity rate = await _context.Rates.FindAsync(rateId).ConfigureAwait(false); if (rate != null) { var removedEntity = _context.Rates.Remove(rate); if (removedEntity?.Entity != null && removedEntity.State.Equals(EntityState.Deleted)) { int deleted = await _context.SaveChangesAsync().ConfigureAwait(false); return(deleted > 0); } } } catch (Exception e) { _context.DetachAll(); _logger.LogError(e, "Exception: {e} // Internal Error while deleting Rate: {rateId}", e.Message, rateId); return(false); } return(false); }
public bool RateRegistration(List <Rate> rates, RateEntity rateEntity) { string tempStr = null; RateHistory = rates; if (!db.CreateRecord <RateEntity>(rateEntity, out tempStr)) { throw new Exception(tempStr); } else { foreach (Rate rate in rates) { rate.EntityID = rateEntity.Id; } db.CreateRecords(rates, out tempStr); Rate minRate = null; Rate maxRate = null; GetMinMax(out minRate, out maxRate, RateHistory); rateEntity.MinRate = minRate; rateEntity.MaxRate = maxRate; AllEntities = db.getCollection <RateEntity>(); db.UpdateRecord <RateEntity>(rateEntity, out tempStr); } return(true); }
/// <summary>Creates a new, empty RateEntity object.</summary> /// <returns>A new, empty RateEntity object.</returns> public override IEntity Create() { IEntity toReturn = new RateEntity(); // __LLBLGENPRO_USER_CODE_REGION_START CreateNewRate // __LLBLGENPRO_USER_CODE_REGION_END return(toReturn); }
public DtoDeparture RegistryDeparture(DtoDeparture departure) { double totalCharge; var departureTime = DateTime.Now; EntryEntity lastEntry = GetInfoEntryByVehicleId(departure.IdVehicle); if (lastEntry == null) { throw new DepartureException("No existe un registro de entrada para el vehículo"); } RateEntity rateEntity = _rateService.GetRateByVehicleType(lastEntry.IdVehicleType); if (rateEntity == null) { throw new DepartureException("No existe una tarifa configurada para el tipo de vehículo"); } var difference = departureTime - lastEntry.EntryTime;//Math.Ceiling((departureTime - lastEntry.EntryTime).TotalHours); int days = difference.Days; double hours = Math.Ceiling(difference.TotalHours); if (days < 1) { if (hours >= rateEntity.DayChargeFrom) { totalCharge = rateEntity.DayValue; } else { totalCharge = rateEntity.HourValue * hours; } } else { var additionalHours = hours % 24; totalCharge = days * rateEntity.DayValue; totalCharge += additionalHours * rateEntity.HourValue; } if (lastEntry.IdVehicleType == VehicleTypeEnum.motorcycle) { bool isParsed = short.TryParse(lastEntry.CC, out short cc); if (!isParsed) { throw new DepartureException("No fue posible determinar el cilindraje del vehículo"); } if (cc >= rateEntity.SpecialChargeFromCC) { totalCharge += rateEntity.SpecialChargeValue; } } var entryEntity = _departureRepository.Add(DepartureMapper.ConvertDTOToEntity(departure, lastEntry, totalCharge)); _cellService.IncreaseCell(lastEntry.IdVehicleType, 1); return(DepartureMapper.ConvertEntityToDTO(entryEntity)); }
//public Rate showSingleUser(int userID) //{ // Rate user = db.getCollection<Rate>().Where(x => x.Id == userID).FirstOrDefault(); // return user; //} public void showMinMax(RateEntity rateEntity) { if (LastEntity == null) { LastEntity = rateEntity; } Console.WriteLine("=============Верхний порог значений==========="); CurrencyComparator(rateEntity.MaxRate.USD_in, LastEntity.MaxRate.USD_in, true); Console.Write("USD IN - USD OUT"); CurrencyComparator(rateEntity.MaxRate.USD_out, LastEntity.MaxRate.USD_out, false); Console.WriteLine("\n"); CurrencyComparator(rateEntity.MaxRate.EUR_in, LastEntity.MaxRate.EUR_in, true); Console.Write("EUR IN - EUR OUT"); CurrencyComparator(rateEntity.MaxRate.EUR_out, LastEntity.MaxRate.EUR_out, false); Console.WriteLine("\n"); CurrencyComparator(rateEntity.MaxRate.RUB_in, LastEntity.MaxRate.RUB_in, true); Console.Write("RUB IN - RUB OUT"); CurrencyComparator(rateEntity.MaxRate.RUB_out, LastEntity.MaxRate.RUB_out, false); Console.WriteLine("\n"); CurrencyComparator(rateEntity.MaxRate.UAH_in, LastEntity.MaxRate.UAH_in, true); Console.Write("UAH IN - UAH OUT"); CurrencyComparator(rateEntity.MaxRate.UAH_out, LastEntity.MaxRate.UAH_out, false); Console.WriteLine("\n"); Console.WriteLine("==============================================="); Console.WriteLine("\n\n"); Console.WriteLine("=============Нижний порог значений==========="); CurrencyComparator(rateEntity.MinRate.USD_in, LastEntity.MinRate.USD_in, true); Console.Write("USD IN - USD OUT"); CurrencyComparator(rateEntity.MinRate.USD_out, LastEntity.MinRate.USD_out, false); Console.WriteLine("\n"); CurrencyComparator(rateEntity.MinRate.EUR_in, LastEntity.MinRate.EUR_in, true); Console.Write("EUR IN - EUR OUT"); CurrencyComparator(rateEntity.MinRate.EUR_out, LastEntity.MinRate.EUR_out, false); Console.WriteLine("\n"); CurrencyComparator(rateEntity.MinRate.RUB_in, LastEntity.MinRate.RUB_in, true); Console.Write("RUB IN - RUB OUT"); CurrencyComparator(rateEntity.MinRate.RUB_out, LastEntity.MinRate.RUB_out, false); Console.WriteLine("\n"); CurrencyComparator(rateEntity.MinRate.UAH_in, LastEntity.MinRate.UAH_in, true); Console.Write("UAH IN - UAH OUT"); CurrencyComparator(rateEntity.MinRate.UAH_out, LastEntity.MinRate.UAH_out, false); Console.WriteLine("\n"); Console.WriteLine("==============================================="); }
protected override async Task Handle(AddRateCommand request, CancellationToken cancellationToken) { var offeringId = request.OfferingKey.DecodeKeyToId(); var offering = await _context.Offerings .FirstOrDefaultAsync(o => o.OfferingId == offeringId && o.EffectiveStartDate <= request.OrderStartDate && o.EffectiveEndDate > request.OrderStartDate); if (offering == null) { throw new ValidationException($"No active offering found for Offering Key '{request.OfferingKey}' and Order Start date of '{request.OrderStartDate}'"); } offering = await _context.Offerings .FirstOrDefaultAsync(o => o.OfferingId == offeringId && o.EffectiveStartDate <= request.OrderEndDate); if (offering == null) { throw new ValidationException($"No active offering found for Offering Key '{request.OfferingKey}' and Order End date of '{request.OrderStartDate}'"); } var rate = new RateEntity { EffectiveStartDate = request.OrderStartDate, EffectiveEndDate = request.OrderEndDate, OfferingId = offeringId, ProductId = request.ProductKey.DecodeKeyToId(), RateClassificationId = request.RateClassificationId, UnitRetailAmount = request.UnitRetailAmount, CommissionAmount = request.CommissionAmount, CommissionPercent = request.CommissionPercent, CostAmount = request.CostAmount, PostageAmount = request.PostageAmount, DeliveryMethodCode = request.DeliveryMethodCode, TermLength = request.TermLength, TermUnit = request.TermUnit, Quantity = request.Quantity, NewRenewalRateIndicator = request.NewRenewalRateIndicator, EffortKey = request.EffortKey, LegacyIdTitleNumber = request.LegacyIdTitleNumber, ListCode = request.ListCode, RateTypeCode = request.RateTypeCode, AddedBy = "ProductAuthority", AddedOnUtc = DateTime.UtcNow }; await _context.Rates.AddAsync(rate); await _context.SaveChangesAndPublishEventsAsync(request.CommandEvents); }
public async Task Run( [QueueTrigger(Constants.RatesAddedQueue)] RateEntity rate, ILogger logger ) { logger.LogInformation($"Handling rate {rate.Ticker}"); var rateDefinitions = Rate.FetchAll(); var definition = rateDefinitions.Single(l => l.Ticker == rate.Ticker); var index = rateDefinitions.IndexOf(definition); var readModelEntity = GetReadModelEntity(rate, definition, index); await readModelEntity.SaveAsync(); }
public void DisplayCurrent() { RateEntity rateEntity = new RateEntity(); List <Rate> rates = DataFetch.GetRecentRate(); Rate minRate = null; Rate maxRate = null; bool temp1 = false; bool temp2 = false; Console.WriteLine("Enter time in minutes to wat until next reload:"); int sleepTime = int.Parse(Console.ReadLine()) * 60000; if (LastEntity != null) { Console.WriteLine("Курсы валют на {0}", DateTime.Now.ToString(System.Globalization.CultureInfo.CreateSpecificCulture("fr-FR"))); showMinMax(LastEntity); } while (true) { Thread.Sleep(sleepTime); GetMinMax(out minRate, out maxRate, rates); AllEntities.ToList(); if (LastEntity != null) { temp1 = LastEntity.MinRate.Equals(minRate); temp2 = LastEntity.MaxRate.Equals(maxRate); } if (!temp1 || !temp2) { Console.Clear(); if (RateRegistration(rates, rateEntity)) { Console.Clear(); Console.WriteLine("Курсы валют на {0}", DateTime.Now.ToString(System.Globalization.CultureInfo.CreateSpecificCulture("fr-FR"))); showMinMax(rateEntity); LastEntity = rateEntity; } else { Console.WriteLine("Something went wrong"); } } } }
public ActionResult AddRate(RateEntity model) { try { // Update model model.User = Request.UserHostAddress; // Update Cloud Table AzureHelper.GetCloudTable("RateEntry").Execute(TableOperation.Insert(model)); // Renew rates DataHelper.AllRates = null; return(Json(model)); } catch (Exception ex) { model.Error = ex.Message; } return(Json(model)); }
public async Task <Rate> GetByIdAsync(int rateId) { try { if (rateId < 0) { throw new ArgumentOutOfRangeException(); } RateEntity entity = await _context.Rates .AsNoTracking() .FirstOrDefaultAsync(x => x.RateId.Equals(rateId)) .ConfigureAwait(false); return(_mapper.Map <Rate>(entity)); } catch (Exception e) { _logger.LogError(e, "Exception: {e} // Internal Error while retrieving rate with Id: {rateId}", e.Message, rateId); return(null); } }
protected override async Task Handle(UpdateRateCommand request, CancellationToken cancellationToken) { //Need clarification on how to validate the time range for Rates var rateId = request.RateKey.DecodeKeyToId(); var offeringId = request.OfferingKey.DecodeKeyToId(); var productId = request.ProductKey.DecodeKeyToId(); var newRate = new RateEntity { RateId = rateId, EffectiveStartDate = request.OrderStartDate, EffectiveEndDate = request.OrderEndDate, RateKey = request.RateKey, OfferingId = offeringId, ProductId = productId, RateClassificationId = request.RateClassificationId, UnitRetailAmount = request.UnitRetailAmount, CommissionAmount = request.CommissionAmount, CommissionPercent = request.CommissionPercent, CostAmount = request.CostAmount, PostageAmount = request.PostageAmount, DeliveryMethodCode = request.DeliveryMethodCode, TermLength = request.TermLength, TermUnit = request.TermUnit, Quantity = request.Quantity, NewRenewalRateIndicator = request.NewRenewalRateIndicator, EffortKey = request.EffortKey, LegacyIdTitleNumber = request.LegacyIdTitleNumber, ListCode = request.ListCode, RateTypeCode = request.RateTypeCode, AddedBy = "ProductAuthority", AddedOnUtc = DateTime.UtcNow }; await _context.AddAsync(newRate); await _context.SaveChangesAsync(); }
public CurrencyEntity Get(Currency currency) { var instance = new CurrencyEntity { Base = currency.Base, Date = currency.Date, Rates = new List <RateEntity>(), LocalSavedDate = DateTime.Now }; foreach (var item in currency.Rates) { var rate = new RateEntity { CurrencyName = item.Key, CurrencyRate = item.Value }; instance.Rates.Add(rate); } return(instance); }
private async Task <bool> InsertNewRateInDBAsync(RateEntity request) { try { using (var client = new HttpClient()) { var insertNewRateInDBAUrl = _api; var response = await client.PostAsJsonAsync( insertNewRateInDBAUrl, request); string resultContent = await response.Content.ReadAsStringAsync(); } } catch (HttpRequestException e) { string postBody = JsonConvert.SerializeObject(request); } return(true); }
private RateEntity GetRate(string fromCurrency, string toCurrency, IList <RateEntity> rates) { // Try to find the conversation var rateConvertion = rates.FirstOrDefault(rate => rate.From == fromCurrency && rate.To == toCurrency); if (rateConvertion != null) { return(rateConvertion); } var rateConversation = GetRateConversation(fromCurrency, toCurrency, rates); var rateDescription = rateConversation.Select(i => i.From).Aggregate((current, next) => current + " - " + next); var rateValue = rateConversation.Select(i => i.Rate).Aggregate((current, next) => current * next); var calculatedRate = new RateEntity { From = rateDescription + " - " + toCurrency, To = toCurrency, Rate = rateValue }; return(calculatedRate); }
public ActionResult RemoveRate(RateEntity model) { try { // Update Cloud Table CloudTable cloudTable = AzureHelper.GetCloudTable("RateEntry"); TableQuery <RateEntity> query = new TableQuery <RateEntity>(); foreach (RateEntity entity in cloudTable.ExecuteQuery(query).Where(r => r.User == Request.UserHostAddress)) { cloudTable.Execute(TableOperation.Delete(entity)); } // Renew rates DataHelper.AllRates = null; return(Json(model)); } catch (Exception ex) { model.Error = ex.Message; } return(Json(model)); }
public static RateEntity CreateRate(DateTime startDate, DateTime endDate, decimal price, LocationEntity location, string description = null, bool isArchive = false) { var rate = new RateEntity { StartDate = startDate, EndDate = endDate, Price = price, Description = description, IsArchive = isArchive, AssignedLocations = new List <RateDetailsEntity>() { new RateDetailsEntity { StreetId = location.StreetId, HouseNumber = location.HouseNumber, BuildingNumber = location.BuildingCorpus, LocationRefId = location.Id } } }; return(rate); }
public static DataHandler SeedData(decimal accrued = 200, decimal received = 100, decimal percent = 25, decimal rate = 166) { var district = new DistrictEntity() { Code = 1, Name = "test" }; var street = new StreetEntity() { DistrictId = district.Id, District = district, StreetName = "1", }; var location = new LocationEntity() { StreetId = street.Id, Street = street, HouseNumber = "1", BuildingCorpus = "2", ApartmentNumber = "3", }; var account = new AccountEntity() { StreetId = street.Id, Account = 1, LocationId = location.Id, Location = location }; var payment = new PaymentDocumentEntity() { AccountId = account.Id, Account = account, Accrued = accrued, Received = received, PaymentDate = DateTime.Now }; var defaultRate = new RateEntity() { Price = Convert.ToDecimal(ConfigurationManager.AppSettings["DefaultPrice"]), IsDefault = true }; var connectionString = ConfigurationManager.ConnectionStrings[ConfigurationManager.AppSettings["ConnectionName"]].ConnectionString; using (var dataBase = new ApplicationDbContext(connectionString)) { dataBase.Database.Delete(); dataBase.Database.Create(); dataBase.Districts.Add(district); dataBase.Streets.Add(street); dataBase.Locations.Add(location); dataBase.Accounts.Add(account); dataBase.PaymentDocuments.Add(payment); dataBase.Rates.Add(defaultRate); dataBase.SaveChanges(); } return(new DataHandler() { AccountEntity = account, StreetEntity = street, LocationEntity = location }); }
public List <Rate> GetRatesByEntity(RateEntity rateEntity) { return(db.getCollection <Rate>().Where(x => x.EntityID == rateEntity.Id).ToList()); }
protected override void Save(RateEntity entity) { _data[entity.Name] = entity; }