private void CheckExchangeRateExists(ExchangeRateResponse exchangeRateResponse, Currency exchangeRate)
 {
     if (exchangeRateResponse.Base.Equals(exchangeRate) == false && exchangeRateResponse.Rates.ContainsKey(exchangeRate) == false)
     {
         throw new Exception("Cannot have exchange rates");
     }
 }
        /// <summary>
        /// Gets the exchangeRates.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        public ExchangeRateResponse GetExchangeRates(ExchangeRateRequest request)
        {
            var response = new ExchangeRateResponse();

            if (request.LoadOptions.Contains("ExchangeRates"))
            {
                if (request.LoadOptions.Contains("IsActive"))
                {
                    response.ExchangeRates = ExchangeRateDao.GetExchangeRatesByActive(true);
                }
                else if (request.LoadOptions.Contains("Date"))
                {
                    response.ExchangeRates = ExchangeRateDao.GetExchangeRatesByDate(request.FromDate, request.ToDate);
                }
                else
                {
                    response.ExchangeRates = ExchangeRateDao.GetExchangeRates();
                }
            }
            if (request.LoadOptions.Contains("ExchangeRate"))
            {
                response.ExchangeRate = request.LoadOptions.Contains("ExchangeRateId")
                    ? ExchangeRateDao.GetExchangeRate(request.ExchangeRateId)
                    : ExchangeRateDao.GetExchangeRatesByDateAndBudgetSource(request.FromDate, request.ToDate,
                                                                            request.BudgetSourceCode);
            }


            return(response);
        }
예제 #3
0
        public async Task <ExchangeRateResponse> Handle(DateTime currentDate)
        {
            var         result   = new ExchangeRateResponse();
            XmlDocument document = await HandleRequest(currentDate);

            if (document != null)
            {
                result.ExchangeRates = HandleDocument(document);
                result.Date          = currentDate;
                return(result);
            }
            return(null);
        }
예제 #4
0
        public IActionResult Index(string query)
        {
            //Создаем наш класс, при этом срабатывает конструктор, который сразу авторизируется в Битрикс24
            // bx_logon = new Bitrix24();

            //Отправляет REST-запрос в Битрикс24, например, получаем список всех задач с помощью команды "task.item.list",
            string TaskListByJSON         = bx_logon.SendCommand("crm.currency.list");
            ExchangeRateResponse response = JsonConvert.DeserializeObject <ExchangeRateResponse>(TaskListByJSON);

            //foreach (var item in response.result)
            //{
            //    Console.WriteLine(item.FULL_NAME + " : " + item.AMOUNT + " руб");
            //}

            return(View(response.result));
        }
예제 #5
0
        public async Task GetExchangeRateAsync_Should_Return_Correct_Exchange_Rate()
        {
            // arrange
            var exchangeRateResponse = new ExchangeRateResponse {
                DestinationCountry = "IN", SourceCountry = "US", ExchangeRate = 70.10m
            };

            _mockProvider.GetExchangeRateAsync("US", "IN", _cxlToken)
            .Returns(Task.FromResult(exchangeRateResponse));

            // act
            var result = await _service.GetExchangeRateAsync("US", "IN", _cxlToken);

            // assert
            Assert.AreEqual(exchangeRateResponse.ExchangeRate, result);
        }
예제 #6
0
        public async Task GetExchangeRateAsync_Should_Return_Correct_Exchange_Rate_With_Markup()
        {
            // arrange
            var exchangeRateResponse = new ExchangeRateResponse {
                DestinationCountry = "IN", SourceCountry = "US", ExchangeRate = 1.0m
            };

            _mockProvider.GetExchangeRateAsync("US", "IN", _cxlToken)
            .Returns(Task.FromResult(exchangeRateResponse));

            _mockMarkupRepository.GetMarkupPercentageAsync("US", "IN", _cxlToken)
            .Returns(Task.FromResult(5m));

            // act
            var result = await _service.GetExchangeRateAsync("US", "IN", _cxlToken);

            // assert
            Assert.AreEqual(0.95, result);
        }
        public async Task <double> GetRateAsync(Currency fromCurrency, Currency toCurrency)
        {
            ExchangeRateResponse response = await GetExchangeRateResponseAsync();

            CheckExchangeRateExists(response, fromCurrency);
            CheckExchangeRateExists(response, toCurrency);

            if (response.Base.Equals(fromCurrency))
            {
                return(response.Rates[toCurrency]);
            }

            if (response.Base.Equals(toCurrency))
            {
                return(1 / response.Rates[fromCurrency]);
            }

            return(response.Rates[fromCurrency] / response.Rates[toCurrency]);
        }
        public ExchangeRateResponse GetExchangeRateInformation(ExchangeRateRequest exchangeRateRequest)
        {
            var exchangeRateResponse = new ExchangeRateResponse();

            try
            {
                exchangeRateResponse = ValidateInput(exchangeRateRequest, exchangeRateResponse);
                if (exchangeRateResponse.Error == null)
                {
                    var exchangerateinput = new ExchangeRateInput
                    {
                        BaseCurrency   = exchangeRateRequest.BaseCurrency,
                        TargetCurrency = exchangeRateRequest.TargetCurrency,
                        Dates          = exchangeRateRequest.Dates
                    };
                    var result = _exchangeRateManager.GetExchangeRateInformation(exchangerateinput);
                    if (result.Error == null)
                    {
                        exchangeRateResponse.MinRate     = result.MinRate;
                        exchangeRateResponse.MaxRate     = result.MaxRate;
                        exchangeRateResponse.AverageRate = result.AverageRate;
                    }
                    else
                    {
                        exchangeRateResponse.Error = new ErrorResponse
                        {
                            ErrorCode    = result.Error.ErrorCode,
                            ErrorMessage = result.Error.ErrorMessage
                        };
                    }
                }
            }
            catch (Exception ex)
            {
                exchangeRateResponse.Error = new ErrorResponse
                {
                    ErrorCode    = HttpStatusCode.InternalServerError,
                    ErrorMessage = ex.Message
                };
            }
            return(exchangeRateResponse);
        }
예제 #9
0
        public ExchangeRateResponse ExchangeRate(ExchangeRateRequest request)
        {
            lock (lockTheEntireGraph)
            {
                var response = new ExchangeRateResponse();

                var spt = new BellmanFord <ExchangeCurrency>(graph, request.Source);
                if (spt.HasNegativeCycle())
                {
                    response.IsCycle = true;

                    var cycle = spt.NegativeCycle();
                    response.Cycle = EdgesToVertexes(cycle);
                    return(response); // TODO: cycle ==> arbitrage opportunity
                }
                if (spt.HasPathTo(request.Destination))
                {
                    response.IsHasPath = true;

                    var    path           = spt.PathTo(request.Destination);
                    var    vertexesOnPath = EdgesToVertexes(path);
                    double rate           = 1;
                    foreach (var edge in path)
                    {
                        rate *= Math.Exp(-edge.Weight);
                    }

                    response.Source      = request.Source;
                    response.Destination = request.Destination;
                    response.Rate        = rate;
                    response.Path        = vertexesOnPath;
                    return(response);
                }
                if (!spt.HasPathTo(request.Destination))
                {
                    response.IsHasPath = false;
                    return(response);
                }

                throw new NotImplementedException();
            }
        }
예제 #10
0
        private async Task <List <ExchangeRateResponse> > getFromRequest(List <DateTime> notExistsDays)
        {
            var result = new List <ExchangeRateResponse>();

            foreach (DateTime notExistsDay in notExistsDays)
            {
                ExchangeRateResponse dayFromRequest = await _xmlRequestProcess.Handle(notExistsDay);

                if (dayFromRequest == null)
                {
                    dayFromRequest = new ExchangeRateResponse()
                    {
                        ExchangeRates = new List <ExchangeRate>(),
                        Date          = notExistsDay
                    };
                }

                _cacheManager.Add(dayFromRequest);
                result.Add(dayFromRequest);
            }

            return(result);
        }
 public void Add(ExchangeRateResponse exchangeRateResponse) => _cache.Set(exchangeRateResponse.Date.cacheDateTimeFormat(), exchangeRateResponse.ExchangeRates.dataObjectToCache());
 /// <summary>
 /// Method to valid input data
 /// </summary>
 /// <param name="exchangeRateRequest"></param>
 /// <param name="exchangeRateResponse"></param>
 /// <returns></returns>
 private ExchangeRateResponse ValidateInput(ExchangeRateRequest exchangeRateRequest, ExchangeRateResponse exchangeRateResponse)
 {
     try
     {
         if (exchangeRateRequest == null)
         {
             exchangeRateResponse.Error = new ErrorResponse
             {
                 ErrorCode    = HttpStatusCode.NoContent,
                 ErrorMessage = ExchangeRateConstant.InvalidInut
             };
         }
         else if (exchangeRateRequest.BaseCurrency == null || string.IsNullOrEmpty(exchangeRateRequest.BaseCurrency.Trim()))
         {
             exchangeRateResponse.Error = new ErrorResponse
             {
                 ErrorCode    = HttpStatusCode.PartialContent,
                 ErrorMessage = ExchangeRateConstant.InvalidBaseCurency
             };
         }
         else if (exchangeRateRequest.TargetCurrency == null || string.IsNullOrEmpty(exchangeRateRequest.TargetCurrency.Trim()))
         {
             exchangeRateResponse.Error = new ErrorResponse
             {
                 ErrorCode    = HttpStatusCode.PartialContent,
                 ErrorMessage = ExchangeRateConstant.InvalidTargetCurrency
             };
         }
         else if (exchangeRateRequest.Dates == null || exchangeRateRequest.Dates.Length == 0)
         {
             exchangeRateResponse.Error = new ErrorResponse
             {
                 ErrorCode    = HttpStatusCode.PartialContent,
                 ErrorMessage = ExchangeRateConstant.InvalidDates
             };
         }
         return(exchangeRateResponse);
     }
     catch (Exception)
     {
         throw;
     }
 }
        /// <summary>
        /// Sets the exchangeRates.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        public ExchangeRateResponse SetExchangeRates(ExchangeRateRequest request)
        {
            var response = new ExchangeRateResponse();

            var exchangeRateEntity = request.ExchangeRate;

            if (request.Action != PersistType.Delete)
            {
                if (!exchangeRateEntity.Validate())
                {
                    foreach (var error in exchangeRateEntity.ValidationErrors)
                    {
                        response.Message += error + Environment.NewLine;
                    }
                    response.Acknowledge = AcknowledgeType.Failure;
                    return(response);
                }
            }
            try
            {
                if (request.Action == PersistType.Insert)
                {
                    using (var scope = new TransactionScope())
                    {
                        //Split exchangeRateEntity.BudgetSourceCode ra mảng để xác định số lần insert
                        var budgetSources = exchangeRateEntity.BudgetSourceCode.Split(',');
                        foreach (string t in budgetSources)
                        {
                            var exchangeRates = ExchangeRateDao.GetExchangeRatesByDateAndBudgetSource(exchangeRateEntity.FromDate, exchangeRateEntity.ToDate, t);
                            if (exchangeRates != null)
                            {
                                response.Acknowledge = AcknowledgeType.Failure;
                                response.Message     = @"Tỷ giá từ ngày " + exchangeRateEntity.FromDate.ToShortDateString() + @" đến ngày " + exchangeRateEntity.ToDate.ToShortDateString() + " của nguồn " + t + " đã tồn tại !";
                                return(response);
                            }
                            exchangeRateEntity.BudgetSourceCode = t;
                            exchangeRateEntity.Description      = "Tỷ giá nguồn " + t + " - Từ ngày " + exchangeRateEntity.FromDate.ToShortDateString() + " Đến ngày " + exchangeRateEntity.ToDate.ToShortDateString();
                            exchangeRateEntity.ExchangeRateId   = ExchangeRateDao.InsertExchangeRate(exchangeRateEntity);
                        }
                        scope.Complete();
                        response.Message = null;
                    }
                }
                else if (request.Action == PersistType.Update)
                {
                    //Kiem tra trung du lieu
                    //lay gia tri cua BudgetSourceCode, dung ham string de split, sau do kiem tra:
                    //1. Neu Count > 1 thi kiem tra phan tu 1 va 2 co giong nhau ko, neu giong nhau thi khong kiem tra gia tri trung, neu khac nhau thi qua buoc 3
                    //2. Kiem tra gia tri trung bang cach truyen vao phan tu thu 2 de kiem tra
                    using (var scope = new TransactionScope())
                    {
                        var budgetSources = exchangeRateEntity.BudgetSourceCode.Split(',');
                        if (budgetSources.Length == 2)
                        {
                            if (budgetSources[0] == budgetSources[1])
                            {
                                exchangeRateEntity.BudgetSourceCode = budgetSources[0];
                                response.Message = ExchangeRateDao.UpdateExchangeRate(exchangeRateEntity);
                            }
                            else
                            {
                                var exchangeRates =
                                    ExchangeRateDao.GetExchangeRatesByDateAndBudgetSource(exchangeRateEntity.FromDate,
                                                                                          exchangeRateEntity.ToDate, budgetSources[1]);
                                if (exchangeRates != null)
                                {
                                    response.Acknowledge = AcknowledgeType.Failure;
                                    response.Message     = @"Tỷ giá từ ngày " +
                                                           exchangeRateEntity.FromDate.ToShortDateString() + @" đến ngày " +
                                                           exchangeRateEntity.ToDate.ToShortDateString() + " của nguồn " +
                                                           budgetSources[1] + " đã tồn tại !";
                                    return(response);
                                }
                                exchangeRateEntity.BudgetSourceCode = budgetSources[1];
                                response.Message = ExchangeRateDao.UpdateExchangeRate(exchangeRateEntity);
                            }
                        }
                        if (response.Message == null)
                        {
                            scope.Complete();
                        }
                    }
                }
                else
                {
                    var exchangeRateForUpdate = ExchangeRateDao.GetExchangeRate(request.ExchangeRateId);
                    response.Message = ExchangeRateDao.DeleteExchangeRate(exchangeRateForUpdate);
                }
            }
            catch (Exception ex)
            {
                response.Acknowledge = AcknowledgeType.Failure;
                response.Message     = ex.Message;
                return(response);
            }
            response.ExchangeRateId = exchangeRateEntity != null ? exchangeRateEntity.ExchangeRateId : 0;
            if (response.Message == null)
            {
                response.Acknowledge  = AcknowledgeType.Success;
                response.RowsAffected = 1;
            }
            else
            {
                response.Acknowledge  = AcknowledgeType.Failure;
                response.RowsAffected = 0;
            }

            return(response);
        }
예제 #14
0
 public SearchController(Bitrix24 bitrix24, ExchangeRateResponse exchangeRateResponse)
 {
     this.bx_logon             = bitrix24;
     this.exchangeRateResponse = exchangeRateResponse;
 }
예제 #15
0
        public ExchangeRateResponse GetData(Dictionary <string, Rates> rates, string targetCurrency)
        {
            var    response    = new ExchangeRateResponse();
            float  maxRate     = 0;
            float  minRate     = float.MaxValue;
            float  averageRate = 0;
            string maxRateDate = "";
            string minRateDate = "";

            float sum = 0;

            foreach (var y in rates)
            {
                Dictionary <string, float> h = new Dictionary <string, float>();

                h.Add("CAD", y.Value.CAD);
                h.Add("HKD", y.Value.HKD);
                h.Add("ISK", y.Value.ISK);
                h.Add("PHP", y.Value.PHP);
                h.Add("DKK", y.Value.DKK);
                h.Add("HUF", y.Value.HUF);
                h.Add("CZK", y.Value.CZK);
                h.Add("AUD", y.Value.AUD);
                h.Add("RON", y.Value.RON);
                h.Add("SEK", y.Value.SEK);
                h.Add("IDR", y.Value.IDR);
                h.Add("INR", y.Value.INR);
                h.Add("BRL", y.Value.BRL);
                h.Add("RUB", y.Value.RUB);
                h.Add("HRK", y.Value.HRK);
                h.Add("JPY", y.Value.JPY);
                h.Add("THB", y.Value.THB);
                h.Add("CHF", y.Value.CHF);
                h.Add("SGD", y.Value.SGD);
                h.Add("PLN", y.Value.PLN);
                h.Add("BGN", y.Value.BGN);
                h.Add("TRY", y.Value.TRY);
                h.Add("CNY", y.Value.CNY);
                h.Add("NOK", y.Value.NOK);
                h.Add("NZD", y.Value.NZD);
                h.Add("ZAR", y.Value.ZAR);
                h.Add("USD", y.Value.USD);
                h.Add("MXN", y.Value.MXN);
                h.Add("ILS", y.Value.ILS);
                h.Add("GBP", y.Value.GBP);
                h.Add("KRW", y.Value.KRW);
                h.Add("MYR", y.Value.MYR);
                h.Add("EUR", y.Value.EUR);

                //float helper = float.Parse(y.GetType().GetProperty(targetCurrency).Name;

                float helper = h.FirstOrDefault(x => x.Key == targetCurrency).Value;

                if (helper > maxRate)
                {
                    maxRate     = helper;
                    maxRateDate = y.Key;
                }
                if (helper < minRate)
                {
                    minRate     = helper;
                    minRateDate = y.Key;
                }

                sum += helper;
            }

            averageRate = sum / rates.Values.Count();

            response.MaxExchangeRate     = maxRate;
            response.MaxExchangeRateDate = maxRateDate;
            response.MinExchangeRate     = minRate;
            response.MinExchangeRateDate = minRateDate;
            response.AverageExchangeRate = averageRate;

            return(response);
        }