예제 #1
0
        public ForexModel MapToJsonModel(string updatedOn, IEnumerable <Rate> rates)
        {
            var currencyModels = new List <CurrencyModel>();

            foreach (var rate in rates)
            {
                var detailsModel = new CurrencyDetailsModel(rate.CurrencyCode, rate.CurrencyName);

                var rateModel = new CurrencyRateModel(
                    rate.BuyRate.ToDouble(),
                    rate.SellRate.ToDouble(),
                    rate.Multiply.ToInt()
                    );

                var guideModel = new CurrencyGuideModel(
                    rate.CurrencyGuide.From,
                    rate.CurrencyGuide.To,
                    rate.CurrencyGuide.Amount.ToInt(),
                    rate.CurrencyGuide.Value.ToDouble()
                    );

                var currencyModel = new CurrencyModel(detailsModel, rateModel, guideModel);

                currencyModels.Add(currencyModel);
            }

            var mappedModel = new ForexModel(DateTime.Parse(updatedOn), currencyModels);

            return(mappedModel);
        }
예제 #2
0
        // async for the case of a request to the database or file
        public async Task <CurrencyRateModel> GetCurrencyInfoAsync(CurrencyEnum currencyFrom, CurrencyEnum currencyTo)
        {
            var currencyRate = new CurrencyRateModel
            {
                CurrencyFrom = currencyFrom,
                CurrencyTo   = currencyTo
            };

            if (currencyFrom == CurrencyEnum.USD)
            {
                currencyRate.Rate = GetRateToUsd(currencyTo);
            }
            else if (currencyTo == CurrencyEnum.USD)
            {
                currencyRate.Rate = 1 / GetRateToUsd(currencyFrom);
            }
            else if (currencyFrom != CurrencyEnum.USD && currencyTo != CurrencyEnum.USD)
            {
                currencyRate.Rate = GetRateToUsd(currencyFrom) / GetRateToUsd(currencyTo);
            }
            else
            {
                throw new ArgumentException("Invalid argument CurrencyEnum passed to GetCurrencyRate method");
            }

            return(currencyRate);
        }
예제 #3
0
        /// <summary>
        /// Currencies the edit.
        /// </summary>
        /// <param name="currencyRate">The currency rate.</param>
        /// <returns>Return a view</returns>
        public async Task <ActionResult> CurrencyEdit(CurrencyRateModel currencyRate)
        {
            try
            {
                var response = await Put("SPCurrencyRate/UpdateCurrency", currencyRate);

                List <CurrencyRateModel> currencyList = new List <CurrencyRateModel>();

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    currencyList = await GetAllCurrencyRate();

                    return(Json(new { Status = 1, Data = RenderRazorViewToString("_CurrencyList", currencyList), Message = response.ReasonPhrase }));
                }
                else
                {
                    return(Json(new { Status = 0, Data = "Error", Message = response.ReasonPhrase }));
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                return(Json(new { Status = 0, Data = "error", Message = ex.Message }));
            }
        }
예제 #4
0
        /// <summary>
        /// Currencies the add.
        /// </summary>
        /// <param name="currencyModel">The currency model.</param>
        /// <returns>Return a view</returns>
        public async Task <ActionResult> CurrencyAdd(CurrencyRateModel currencyModel)
        {
            try
            {
                var currency = currencyMapper.ToEntity(currencyModel);
                var response = await Post("SPCurrencyRate/CreateCurrencyDescription", currency);

                List <CurrencyRateModel> currencyList = new List <CurrencyRateModel>();
                currencyList = await GetAllCurrencyRate();

                if (response.StatusCode == HttpStatusCode.Created)
                {
                    return(Json(new { Status = 1, Data = RenderRazorViewToString("_CurrencyList", currencyList), Message = response.ReasonPhrase }));
                }
                else
                {
                    return(Json(new { Status = 0, Data = "Error", Message = response.ReasonPhrase }));
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                return(Json(new { Status = 0, Data = "error", Message = ex.Message }));
            }
        }
예제 #5
0
        public async Task <CurrencyRateModel[]> GetDynamics(string charCode, DateTime start, DateTime end)
        {
            CurrencyRateModel currencyRate = await GetCurrencyRate(charCode, start);

            string xmlResponse = await CallApi(() => _currencyRatesDynamicsApiUrl
                                               .SetQueryParams(new
            {
                date_req1 = GetFormattedDate(start),
                date_req2 = GetFormattedDate(end),
                VAL_NM_RQ = currencyRate.Id,
            })
                                               .GetStringAsync());

            var response = XmlUtils.ParseXml <RubCurrencyDynamicsResponse>(xmlResponse);

            return(response.Records.Select(x => new CurrencyRateModel
            {
                Id = currencyRate.Id,
                Name = currencyRate.Name,
                CharCode = charCode,
                Date = x.Date,
                Nominal = x.Nominal,
                Rate = x.Rate,
            }).ToArray());
        }
예제 #6
0
        public bool InsertCurrencyRate(CurrencyRateModel currencyRateModel)
        {
            var isSuccess    = false;
            var sqlStatement =
                string.Format("INSERT INTO tb_valute ([ValuteId], [NumCode], [CharCode], [Nominal], [Name], [Value])" +
                              "VALUES ('{0}', '{1}', '{2}', {3}, N'{4}', {5})",
                              currencyRateModel.ValuteId,
                              currencyRateModel.NumCode,
                              currencyRateModel.CharCode,
                              currencyRateModel.Nominal,
                              currencyRateModel.Name,
                              currencyRateModel.Value.ToStingWithDot());

            using (var sqlCommand = new SqlCommand(sqlStatement, _sqlConnection))
            {
                try
                {
                    sqlCommand.ExecuteNonQuery();
                    isSuccess = true;
                }
                catch (Exception exception)
                {
                    var errorHandler = new Logger();
                    errorHandler.Error(exception);
                }
            }

            return(isSuccess);
        }
예제 #7
0
        public IActionResult Details(int id)
        {
            var Currency     = currenciesService.ReadCurrency(id);
            var ExchangeRate = exchangeRateService.ReadExchangeRate(id);

            var CurrencyRateModel = new CurrencyRateModel();

            CurrencyRateModel.Currency     = Currency;
            CurrencyRateModel.ExchangeRate = ExchangeRate;

            return(View(CurrencyRateModel));
        }
        public void ConvertToLocal_ZeroAmount_ReturnsZero()
        {
            // arrange
            var amount   = 0;
            var rateMode = new CurrencyRateModel
            {
                Nominal = 1,
                Rate    = 1,
            };

            // act
            var result = CurrenciesConverter.ConvertToLocal(amount, rateMode);

            // assert
            result.Should().Be(0m);
        }
        public void ConvertToLocal_OneToOne_ReturnsInitialAmount()
        {
            // arrange
            var amount   = 100;
            var rateMode = new CurrencyRateModel
            {
                Nominal = 1,
                Rate    = 1
            };

            // act
            var result = CurrenciesConverter.ConvertToLocal(amount, rateMode);

            // assert
            result.Should().Be(amount);
        }
예제 #10
0
        public void ConvertToLocal_NegativeRate_ReturnsNegativeResult()
        {
            // arrange
            var amount   = 100;
            var rateMode = new CurrencyRateModel
            {
                Nominal = 1,
                Rate    = -100,
            };

            // act
            var result = CurrenciesConverter.ConvertToLocal(amount, rateMode);

            // assert
            result.Should().Be(-10000m);
        }
예제 #11
0
        public void ConvertToLocal_ZeroNominal_ThrowsException()
        {
            // arrange
            var amount   = 100;
            var rateMode = new CurrencyRateModel
            {
                Nominal = 0,
                Rate    = 1,
            };

            // act
            Action action = () => CurrenciesConverter.ConvertToLocal(amount, rateMode);

            // assert
            action.Should().Throw <DivideByZeroException>();
        }
예제 #12
0
        public void ConvertToLocal_Always_ReturnsResult(
            decimal amount, double rate, int nominal, decimal expectedResult)
        {
            // arrange
            var rateMode = new CurrencyRateModel
            {
                Nominal = nominal,
                Rate    = rate,
            };

            // act
            var result = CurrenciesConverter.ConvertToLocal(amount, rateMode);

            // assert
            result.Should().Be(expectedResult);
        }
예제 #13
0
        /// <summary>
        /// Add user popup
        /// </summary>
        /// <returns>Return a view</returns>
        public async Task <ActionResult> AddCurrencyRatePopUp()
        {
            try
            {
                CurrencyRateModel currencyRate = new CurrencyRateModel();
                var response = await Get("SPCurrencyRate/GetAllCurrencyRate");

                currencyRate.SymbolId = await GetAllCurrency();

                currencyRate.Rate = 1;
                return(Json(new { Status = 1, Data = RenderRazorViewToString("_AddCurrencyRatePopUp", currencyRate) }));
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                return(Json(new { Status = 0, Data = "error", Message = ex.Message }));
            }
        }
예제 #14
0
        /// <summary>
        /// Gets the currency rate by identifier.
        /// </summary>
        /// <param name="userId">The user identifier.</param>
        /// <returns>Model CurrencyRateModel</returns>
        public async Task <CurrencyRateModel> GetCurrencyRateById(int userId)
        {
            CurrencyRateModel currencyRate = new CurrencyRateModel();

            try
            {
                var response = await Get("SPCurrencyRate/GetCurrency/" + userId);

                if (response.IsSuccessStatusCode)
                {
                    currencyRate = currencyMapper.ToObject(await response.Content.ReadAsAsync <SPCurrencyRateDto>());
                }

                currencyRate.SymbolId = await GetAllCurrency();

                return(currencyRate);
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                return(null);
            }
        }
예제 #15
0
        public async Task <IActionResult> UpdateCurrencyRate([FromBody] CurrencyRateModel model)
        {
            try
            {
                var currencyRate = await service.GetCurrencyRateById(model.Id);

                currencyRate.Rate = model.Rate;
                currencyRate.SetModifyByAndModifyDate(model.User);
                await service.UpdateCurrencyRate(currencyRate);

                return(Ok(new Response {
                    Status = "Success", Message = "Rate updated successfully"
                }));
            }
            catch (System.Exception ex)
            {
                return(BadRequest(new Response
                {
                    Status = "Error",
                    Message = ex.Message
                }));
            }
        }
예제 #16
0
        public List <CurrencyRateModel> GetCurrencyRatesForProcessing()
        {
            List <CurrencyRateModel> models = new List <CurrencyRateModel>();

            using (SqlConnection conn = new SqlConnection(_connectionString))
            {
                conn.Open();

                SqlCommand cmd = new SqlCommand("dbo.GetCurrencyRates", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataReader reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    CurrencyRateModel model = new CurrencyRateModel();
                    Rate rate = new Rate();
                    model.BankId        = reader["ProcessingId"] != DBNull.Value ? Convert.ToInt32(reader["ProcessingId"]) : 0;
                    rate.CurrencyInISO  = reader["CurrencyInISO"] != DBNull.Value ? Convert.ToString(reader["CurrencyInISO"]) : string.Empty;
                    rate.CurrencyOutISO = reader["CurrencyOutISO"] != DBNull.Value ? Convert.ToString(reader["CurrencyOutISO"]) : string.Empty;
                    rate.SellingRate    = reader["SellingRate"] != DBNull.Value ? Convert.ToDouble(reader["SellingRate"]) : 0;
                    rate.PurchanseRate  = reader["PurchanseRate"] != DBNull.Value ? Convert.ToDouble(reader["PurchanseRate"]) : 0;

                    if (models.Where(m => m.BankId == model.BankId).Count() > 0)
                    {
                        models.Where(m => m.BankId == model.BankId).FirstOrDefault().Rates.Add(rate);
                    }
                    else
                    {
                        model.Rates = new List <Rate>();
                        model.Rates.Add(rate);
                        models.Add(model);
                    }
                }
            }
            return(models);
        }
예제 #17
0
        public async Task <double> GetCurrencyRate(string charCode, DateTime?onDate)
        {
            CurrencyRateModel rate = await GetCurrencyRateInternal(charCode, onDate);

            return(rate?.Rate ?? 0d);
        }
예제 #18
0
        public async Task GetDynamics_Always_ReturnDynamics()
        {
            // arrange
            using var httpTest = new HttpTest();

            var      ondate   = DateTime.Now;
            string   charCode = "USD";
            DateTime start    = new DateTime(2021, 01, 01);
            DateTime end      = new DateTime(2021, 01, 03);

            //https://www.nbrb.by/API/ExRates/Rates/Dynamics/145?startDate=2021-1-1&endDate=2021-1-3

            httpTest
            .ForCallsTo("https://www.nbrb.by/api/exrates/currencies")
            .WithVerb(HttpMethod.Get)
            .RespondWith("[{ \"Cur_ID\":145,\"Cur_ParentID\":145,\"Cur_Code\":" +
                         "\"840\",\"Cur_Abbreviation\":\"USD\",\"Cur_Name\":\"Доллар США\"}]");

            httpTest
            .ForCallsTo("https://www.nbrb.by/api/exrates/rates/dynamics/145")
            .WithVerb(HttpMethod.Get)
            .WithQueryParam("startdate", start.ToString())
            .WithQueryParam("enddate", end.ToString())
            .RespondWith(
                "[{ \"Cur_ID\":145,\"Date\":\"2021-01-01T00:00:00\",\"Cur_OfficialRate\":2.5789}," +
                "{ \"Cur_ID\":145,\"Date\":\"2021-01-02T00:00:00\",\"Cur_OfficialRate\":2.5789}," +
                "{ \"Cur_ID\":145,\"Date\":\"2021-01-03T00:00:00\",\"Cur_OfficialRate\":2.5789}]");

            // act
            var api    = new BynCurrenciesApi();
            var result = await api.GetDynamics(charCode, start, end);

            // assert
            var result1 = new CurrencyRateModel[3]
            {
                new CurrencyRateModel
                {
                    Date     = new DateTime(2021, 01, 01),
                    Id       = "145",
                    Name     = "Доллар США",
                    Nominal  = 0,
                    Rate     = 2.5789,
                    CharCode = "USD",
                },
                new CurrencyRateModel
                {
                    Date     = new DateTime(2021, 01, 02),
                    Id       = "145",
                    Name     = "Доллар США",
                    Nominal  = 0,
                    Rate     = 2.5789,
                    CharCode = "USD",
                },
                new CurrencyRateModel
                {
                    Date     = new DateTime(2021, 01, 03),
                    Id       = "145",
                    Name     = "Доллар США",
                    Nominal  = 0,
                    Rate     = 2.5789,
                    CharCode = "USD",
                },
            };

            result.Should().BeEquivalentTo(result1);
        }
예제 #19
0
        public void IntegrationTest()
        {
            var connection = TestSession.GetConnection();

            connection.Open();
            #region good insertion and select by id test
            CurrencyRateModel inserted = new CurrencyRateModel();
            inserted.CurrencyRateDate = TestSession.Random.RandomDateTime();
            inserted.FromCurrencyCode = TestSession.Random.RandomString(3);
            inserted.ToCurrencyCode   = TestSession.Random.RandomString(3);
            inserted.AverageRate      = TestSession.Random.RandomDecimal();
            inserted.EndOfDayRate     = TestSession.Random.RandomDecimal();
            inserted.ModifiedDate     = TestSession.Random.RandomDateTime();

            _tested.Insert(connection, new[] { inserted });

            var selectedAfterInsertion = _tested.GetByPrimaryKey(connection, new CurrencyRateModelPrimaryKey()
            {
                CurrencyRateID = inserted.CurrencyRateID,
            });

            CollectionAssert.IsNotEmpty(selectedAfterInsertion);
            var selectedAfterInsert = selectedAfterInsertion.Single();
            Assert.AreEqual(inserted.CurrencyRateID, selectedAfterInsert.CurrencyRateID);
            Assert.AreEqual(inserted.CurrencyRateDate, selectedAfterInsert.CurrencyRateDate);
            Assert.AreEqual(inserted.FromCurrencyCode, selectedAfterInsert.FromCurrencyCode);
            Assert.AreEqual(inserted.ToCurrencyCode, selectedAfterInsert.ToCurrencyCode);
            Assert.AreEqual(inserted.AverageRate, selectedAfterInsert.AverageRate);
            Assert.AreEqual(inserted.EndOfDayRate, selectedAfterInsert.EndOfDayRate);
            Assert.AreEqual(inserted.ModifiedDate, selectedAfterInsert.ModifiedDate);

            #endregion

            #region update and select by id test
            inserted.CurrencyRateDate = TestSession.Random.RandomDateTime();
            inserted.FromCurrencyCode = TestSession.Random.RandomString(3);
            inserted.ToCurrencyCode   = TestSession.Random.RandomString(3);
            inserted.AverageRate      = TestSession.Random.RandomDecimal();
            inserted.EndOfDayRate     = TestSession.Random.RandomDecimal();
            inserted.ModifiedDate     = TestSession.Random.RandomDateTime();

            _tested.Update(connection, new[] { inserted });

            var selectedAfterUpdateAddresss = _tested.GetByPrimaryKey(connection, new CurrencyRateModelPrimaryKey()
            {
                CurrencyRateID = inserted.CurrencyRateID,
            });

            CollectionAssert.IsNotEmpty(selectedAfterUpdateAddresss);
            var selectedAfterUpdate = selectedAfterUpdateAddresss.Single();
            Assert.AreEqual(inserted.CurrencyRateID, selectedAfterUpdate.CurrencyRateID);
            Assert.AreEqual(inserted.CurrencyRateDate, selectedAfterUpdate.CurrencyRateDate);
            Assert.AreEqual(inserted.FromCurrencyCode, selectedAfterUpdate.FromCurrencyCode);
            Assert.AreEqual(inserted.ToCurrencyCode, selectedAfterUpdate.ToCurrencyCode);
            Assert.AreEqual(inserted.AverageRate, selectedAfterUpdate.AverageRate);
            Assert.AreEqual(inserted.EndOfDayRate, selectedAfterUpdate.EndOfDayRate);
            Assert.AreEqual(inserted.ModifiedDate, selectedAfterUpdate.ModifiedDate);

            #endregion

            #region delete test
            _tested.Delete(connection, new[] { inserted });
            var selectedAfterDeleteAddresss = _tested.GetByPrimaryKey(connection, new CurrencyRateModelPrimaryKey()
            {
                CurrencyRateID = inserted.CurrencyRateID,
            });
            CollectionAssert.IsEmpty(selectedAfterDeleteAddresss);
            #endregion
            connection.Close();
        }
예제 #20
0
 private CurrencyItemViewModel()
 {
     Currencies       = new List <string>(CurrencyRateModel.GetAllCurrencysName());
     SelectedCurrency = Currencies.FirstOrDefault();
 }
예제 #21
0
 public static decimal ConvertFromLocal(decimal amount, CurrencyRateModel rate)
 {
     return(amount / (decimal)rate.Rate * rate.Nominal);
 }
예제 #22
0
 public static decimal ConvertToLocal(decimal amount, CurrencyRateModel rate)
 {
     return(amount * (decimal)rate.Rate / (rate.Nominal));
 }