示例#1
0
        public async Task <ActionResult> SaveAsync(List <ExchangeRateViewModel> exchangeRates)
        {
            if (!ModelState.IsValid)
            {
                return(this.InvalidModelState(this.ModelState));
            }

            if (exchangeRates == null || exchangeRates.Count().Equals(0))
            {
                return(this.InvalidModelState(this.ModelState));
            }



            var meta = await AppUsers.GetCurrentAsync().ConfigureAwait(true);

            int    officeId     = meta.OfficeId;
            string baseCurrency = meta.CurrencyCode;



            long id = await ExchangeRates.SaveAsync(this.Tenant, officeId, baseCurrency, exchangeRates).ConfigureAwait(false);

            return(this.Ok(id));
        }
示例#2
0
        public List <DB_ExchangeRate> Map_ExchangeRates_ToDBModelList(ExchangeRates exchangeRates)
        {
            List <DB_ExchangeRate> result = new List <DB_ExchangeRate>();

            string[] countryCodes = ConfigurationManager.AppSettings["CountryCodesToRecord"].Split(';');

            if (countryCodes.Contains("GB"))
            {
                result.Add(Return_GBPExchangeRate_ToModel());
            }

            foreach (ExchangeRate _exchangeRate in exchangeRates.Exchange_Rates)
            {
                if (countryCodes.Contains(_exchangeRate.To_Country_Code))
                {
                    DB_ExchangeRate _newExchangeRate = new DB_ExchangeRate()
                    {
                        FROM_COUNTRY_CODE  = _exchangeRate.From_Country_Code,
                        FROM_CURRENCY      = _exchangeRate.From_Currency_Code,
                        TO_COUNTRY_CODE    = _exchangeRate.To_Country_Code,
                        TO_CURRENCY        = _exchangeRate.To_Currency_Code,
                        EFFECTIVE_DATE     = exchangeRates.Effective_Date,
                        EXCHANGE_RATE      = _exchangeRate.Rate_of_Exchange,
                        LAST_UPDATE_USR_ID = "HMRC_Update"
                    };

                    result.Add(_newExchangeRate);
                }
            }

            return(result);
        }
        public async Task <ActionResult <ExchangeRates> > AddExchangeRate(ExchangeRates exchangeRates)
        {
            _context.ExchangeRates.Add(exchangeRates);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetExchangeRates", new { id = exchangeRates.Id }, exchangeRates));
        }
        public async Task <IActionResult> UpdateExchangeRate(int id, ExchangeRates exchangeRates)
        {
            if (id != exchangeRates.Id)
            {
                return(BadRequest());
            }

            _context.Entry(exchangeRates).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ExchangeRatesExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
示例#5
0
        public async Task <ActionResult <ExchangeRates> > GetExchangeRate(string @base,
                                                                          [FromQuery(Name = "target")] string[] target)
        {
            try
            {
                if (string.IsNullOrEmpty(@base))
                {
                    throw new ArgumentException("Base currency couldn't be empty.", nameof(@base));
                }
                if ((!(target is null) && target.All(t => string.IsNullOrEmpty(t))))
                {
                    throw new ArgumentException("Target currencies contains invalid value.",
                                                nameof(target));
                }

                ExchangeRates exchangeRate =
                    await _exchangeRateProcessor.GetExchangeRateAsync(@base, target);

                return(exchangeRate);
            }
            catch (Exception ex)
            {
                Console.WriteLine($@"Exception occured: {ex}");
                return(BadRequest(new[] { ex.Message, @base, string.Join(',', target) }));
            }
        }
示例#6
0
        private async void GetRates()
        {
            try
            {
                var client = new HttpClient();
                client.BaseAddress = new Uri("https://openexchangerates.org");
                var url      = "/api/latest.json?app_id=c5ad6fcb983f45448075f48c7cfc32f0";
                var response = await client.GetAsync(url);

                if (!response.IsSuccessStatusCode)
                {
                    await App.Current.MainPage.DisplayAlert("Error", response.StatusCode.ToString(), "Aceptar");

                    IsRunning = false;
                    IsEnabled = false;
                    return;
                }

                var result = await response.Content.ReadAsStringAsync();

                exchangeRates = JsonConvert.DeserializeObject <ExchangeRates>(result);
            }
            catch (Exception ex)
            {
                await App.Current.MainPage.DisplayAlert("Error", ex.Message, "Aceptar");

                IsRunning = false;
                IsEnabled = false;
                return;
            }

            LoadRates();
            IsRunning = false;
            IsEnabled = true;
        }
示例#7
0
 private Task <ExchangeRatesViewModel> LoadExchangeRatesViewModel(ExchangeRates rates)
 {
     return(Task.Run(() =>
     {
         return new ExchangeRatesViewModel(rates);
     }));
 }
示例#8
0
        public void AreAllRates()
        {
            //Arrange
            Currency[]    currencies = new Currency[] { Currency.AUD, Currency.CAD, Currency.CHF, Currency.EUR, Currency.GBP, Currency.JPY, Currency.USD };
            ExchangeRates rates      = new ExchangeRates();
            string        res        = "";
            decimal       rate       = 0;

            //Act
            for (int i = 0; i < currencies.Length; i++)
            {
                for (int j = 0; j < currencies.Length; j++)
                {
                    try
                    {
                        rate = rates.GetRate(currencies[i], currencies[j]);
                    }
                    catch
                    {
                        res += currencies[i].ToString() + "-" + currencies[j].ToString() + "|";
                    }
                    if (i == j && rate != 1m)
                    {
                        res += currencies[i].ToString() + "-" + currencies[j].ToString() + "|";
                    }
                }
            }

            //Assert
            Assert.AreEqual("", res);
        }
示例#9
0
        private static List <ExchangeRates> LoadRates(string html)
        {
            List <ExchangeRates> rates = new List <ExchangeRates>();
            HtmlWeb web     = new HtmlWeb();
            var     htmlDoc = web.Load(html);

            var nodes = htmlDoc.DocumentNode.SelectNodes("//tbody//tr").ToList();

            int index = 0;

            foreach (var tableRow in nodes)
            {
                try
                {
                    var name           = tableRow.SelectNodes("..//th//a//div[@data-type='" + class_to_get_name + "']").ToArray()[index].InnerHtml;
                    var value          = tableRow.SelectNodes("..//td[@data-type='" + class_to_get_value + "']//span").ToArray()[index].InnerHtml;
                    var lastDateUpdate = tableRow.SelectNodes("..//td[@data-type='" + class_to_get_time + "']//span").ToArray()[index].InnerHtml;
                    var _exchange      = new ExchangeRates()
                    {
                        Name = name, Value = Convert.ToDouble(value), LastUpdate = lastDateUpdate
                    };
                    rates.Add(_exchange);
                    index++;
                }
                catch (Exception ex)
                {
                    index++;
                    continue;
                }
            }
            return(rates);
        }
        /// <summary>
        /// Read data from the stream and extract useful information from it
        /// </summary>
        /// <param name="exchangeRatesForDates"></param>
        /// <param name="stream"></param>
        /// <returns>A list of exchange rates retrieved from the api</returns>
        private static async Task <List <ExchangeRates> > ExtractDataFromStreamAsync(List <ExchangeRates> exchangeRatesForDates, Stream stream)
        {
            var jsonString = await Utility.Utility.StreamToStringAsync(stream);

            Dictionary <string, string> rates = Utility.Utility.GetJsonDataFromString(jsonString);

            foreach (var rateValues in rates.Values)
            {
                Dictionary <string, string> dates = Utility.Utility.GetJsonDataFromString(rateValues);

                foreach (var dateValues in dates.Values)
                {
                    Dictionary <string, string> currencies = Utility.Utility.GetJsonDataFromString(dateValues);

                    var exRate = new ExchangeRates()
                    {
                        CurrenyOnDate     = Convert.ToDateTime(dates.Keys.First()),
                        FromCurrencyName  = currencies.Keys.First().ToString(),
                        FromCurrencyValue = Convert.ToDouble(currencies.Values.First()),
                        ToCurrencyName    = currencies.Keys.Last().ToString(),
                        ToCurrencyValue   = Convert.ToDouble(currencies.Values.Last())
                    };

                    exchangeRatesForDates.Add(exRate);
                }

                break; // we only need the rates object from rates.values
            }

            return(exchangeRatesForDates);
        }
示例#11
0
        public IActionResult BaseMethod(ExchangeRates dbValue, string?Base, string?symbols)
        {
            dynamic exo      = new ExpandoObject();
            decimal baseRate = 0;

            if (Base != "")
            {
                var found = false;
                dbValue.currencies.ForEach((cur) =>
                {
                    if (cur.currency == Base.ToUpper())
                    {
                        found    = true;
                        baseRate = cur.rate;
                    }
                });

                if (!found && Base.ToUpper() != "EUR")
                {
                    return(BadRequest());
                }

                exo = Check(dbValue, Base, exo, baseRate, symbols);
                return(Ok(new { timestamp = (dbValue.date - Epoch).TotalSeconds, source = Base.ToUpper(), quotes = exo }));
            }
            else
            {
                Base = "EUR";
                exo  = Check(dbValue, Base, exo, baseRate, symbols);
                return(Ok(new { timestamp = (dbValue.date - Epoch).TotalSeconds, source = Base.ToUpper(), quotes = exo }));
            }
        }
示例#12
0
        private void NewRate(LatestPriceResultMessage result)
        {
            UiDispatcher.Invoke(() =>
            {
                var e = ExchangeRates.FirstOrDefault(x => x.IsSimilarRequest(result));
                if (e != null)
                {
                    ExchangeRates.Remove(e);
                }
                ExchangeRates.Add(result);

                var exrs = ExchangeRates.OrderBy(x => x.Pair.ToString()).ToList();
                ExchangeRates.Clear();

                foreach (var er in exrs)
                {
                    ExchangeRates.Add(er);
                }

                if (AssetLeft.IsNone() || AssetRight.IsNone() || ConvertLeft == 0)
                {
                    return;
                }

                var ap = new AssetPair(AssetLeft, AssetRight);
                if (!result.Pair.Equals(ap))
                {
                    return;
                }

                _isConverted    = result.IsConverted;
                ResultViewModel = new ExchangeRateResultViewModel(this, result);
                LoadingInfo     = "";
            });
        }
示例#13
0
        private async void LoadExchangeRateList()
        {
            if (isExchangeRateListLoaded)
            {
                return;
            }

            if (queryDispatcher == null)
            {
                return;
            }

            List <ExchangeRateModel> exchangeRates = await queryDispatcher.QueryAsync(new ListTargetCurrencyExchangeRates(UniqueCode));

            if (exchangeRates == null)
            {
                return;
            }

            ExchangeRates.AddRange(exchangeRates);
            ExchangeRates.SortDescending(e => e.ValidFrom);
            RaisePropertyChanged(nameof(ExchangeRates));

            isExchangeRateListLoaded = true;
        }
示例#14
0
        public async Task UpdateTable()
        {
            var ResultCount = await GetAll();

            if (ResultCount.Count() > 0)
            {
                int z = 0;

                foreach (var x in ResultCount)
                {
                    x.ccy      = ApiPrivatBank.exchangeRatesModel[z].ccy;
                    x.base_ccy = ApiPrivatBank.exchangeRatesModel[z].base_ccy;
                    x.buy      = ApiPrivatBank.exchangeRatesModel[z].buy;
                    x.sale     = ApiPrivatBank.exchangeRatesModel[z].sale;
                    x.Date     = ApiPrivatBank.exchangeRatesModel[z].Date;

                    ExchangeRates exchangeRates = Mapper.Map <ExchangeRatesBll, ExchangeRates>(x);
                    _unitOfWork.ExchangeRatesUnitOfWork.Update(exchangeRates);
                    await _unitOfWork.Save();

                    z++;
                }
            }
            else
            {
                await Insert(ApiPrivatBank.exchangeRatesModel);
            }
        }
示例#15
0
        public async Task <IHttpActionResult> CreateExchangeRates(Models.ExRatesByUser info)
        {
            string usdPur  = info.USDPurchase.Replace('.', ',');
            string eurPur  = info.EURPurchase.Replace('.', ',');
            string usdSale = info.USDSale.Replace('.', ',');
            string eurSale = info.EURSale.Replace('.', ',');

            double usdPurchase = Convert.ToDouble(usdPur);
            double eurPurchase = Convert.ToDouble(eurPur);
            double usdSalee    = Convert.ToDouble(usdSale);
            double eurSalee    = Convert.ToDouble(eurSale);

            ExchangeRates rates = new ExchangeRates
            {
                BankId      = info.BankId,
                USDPurchase = usdPurchase,
                USDSale     = usdSalee,
                EURPurchase = eurPurchase,
                EURSale     = eurSalee
            };

            try
            {
                await _exchangeRatesService.RemoveExchangeRatesByBankIdAsync(info.BankId);

                await _exchangeRatesService.SaveExchangeRatesAsync(rates);
            }
            catch (Exception)
            {
                return(InternalServerError());
            }

            return(Ok());
        }
        public void ExchangeRates_ConvertAmountToUSD_UnitTest()
        {
            var exchangeRates = new ExchangeRates(mockServiceWrapper.Object);
            var rate          = exchangeRates.ConvertValue(100, "USD", "EUR");

            Assert.IsTrue(rate == 300);
        }
示例#17
0
 public async Task Execute(IJobExecutionContext context)
 {
     Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
     XDocument xml = XDocument.Load("http://www.cbr.ru/scripts/XML_daily.asp");
     ExchangeRates exchangeRatesUSD = new ExchangeRates { Id = "R01235", Name = "USD" };
     ExchangeRates exchangeRatesEUR = new ExchangeRates { Id = "R01239", Name = "EUR" };
     ExchangeRates exchangeRatesCNY = new ExchangeRates { Id = "R01375", Name = "CNY" };
     ExchangeRates exchangeRatesJPY = new ExchangeRates { Id = "R01820", Name = "JPY" };
     exchangeRatesUSD.Value = Convert.ToDecimal(xml.Elements("ValCurs").Elements("Valute").FirstOrDefault(x => x.Element("NumCode").Value == "840").Elements("Value").FirstOrDefault().Value);
     exchangeRatesEUR.Value = Convert.ToDecimal(xml.Elements("ValCurs").Elements("Valute").FirstOrDefault(x => x.Element("NumCode").Value == "978").Elements("Value").FirstOrDefault().Value);
     exchangeRatesCNY.Value = Convert.ToDecimal(xml.Elements("ValCurs").Elements("Valute").FirstOrDefault(x => x.Element("NumCode").Value == "156").Elements("Value").FirstOrDefault().Value);
     exchangeRatesJPY.Value = Convert.ToDecimal(xml.Elements("ValCurs").Elements("Valute").FirstOrDefault(x => x.Element("NumCode").Value == "392").Elements("Value").FirstOrDefault().Value);
     List<ExchangeRates> exchangeRates = new List<ExchangeRates> { exchangeRatesUSD, exchangeRatesEUR, exchangeRatesCNY, exchangeRatesJPY };
     string connectionString = @"Server=.\SQLEXPRESS;Database=TestDataBase;Trusted_Connection=True;MultipleActiveResultSets=true";
     string commandread = "insert [ExchangeRates] ([CurrenciesId], [Value], [Date]) values (@currenciesid, @value, @date)";
     using (SqlConnection connection = new SqlConnection(connectionString))
     {
         await connection.OpenAsync();
         foreach (var exRate in exchangeRates)
         {
             SqlCommand command = new SqlCommand(commandread, connection);
             SqlParameter currenciesidParameter = new SqlParameter("@currenciesid", exRate.Id);
             SqlParameter valueParameter = new SqlParameter("@value", exRate.Value);
             SqlParameter dateParameter = new SqlParameter("@date", DateTime.Now);
             command.Parameters.Add(currenciesidParameter);
             command.Parameters.Add(valueParameter);
             command.Parameters.Add(dateParameter);
             int number = await command.ExecuteNonQueryAsync();
         }
     }
     Console.WriteLine($"Добавлен курс на дату: {DateTime.Now}");
 }
示例#18
0
        private async void LoadRate()
        {
            IsRunning = true;
            try
            {
                var client = new HttpClient();
                client.BaseAddress = new Uri("https://openexchangerates.org");
                var url      = "/api/latest.json?app_id=f490efbcd52d48ee98fd62cf33c47b9e";
                var response = await client.GetAsync(url);

                if (!response.IsSuccessStatusCode)
                {
                    Message   = response.StatusCode.ToString();
                    IsRunning = false;
                    return;
                }

                var result = await response.Content.ReadAsStringAsync();

                exchangeRates = JsonConvert.DeserializeObject <ExchangeRates>(result);
            }
            catch (Exception ex)
            {
                Message   = ex.Message;
                IsRunning = false;
                return;
            }
            ConvertRates();

            IsRunning = false;
            IsEnabled = true;
        }
        public void EtherExchangeRateUpdate()
        {
            Currency rates = currencyAPI.getLatestRates();

            Console.WriteLine("1 Euro is equal to " + rates.rates.USD + " US Dollars");
            APIStats EtherRate = etherAPI.getEtherToUSD();
            double   EtherUSD  = EtherRate.result.ethusd;

            Console.WriteLine("The current rate of Ether in US Dollars is " + EtherUSD);
            double EtherToEuro = EtherUSD / rates.rates.USD;// converts ether usd to ether euro the base for api request.

            using (var context = new ApplicationDbContext())
            {
                ExchangeRates newRates = new ExchangeRates();
                newRates.TimeStamp   = rates.timestamp;
                newRates.EtherToUSD  = EtherUSD;
                newRates.EtherToEuro = EtherToEuro;
                newRates.EtherToAUD  = EtherToEuro * rates.rates.AUD;
                newRates.EtherToCAD  = EtherToEuro * rates.rates.CAD;
                newRates.EtherToCNY  = EtherToEuro * rates.rates.CNY;
                newRates.ETherToGBP  = EtherToEuro * rates.rates.GBP;
                newRates.EtherToJPY  = EtherToEuro * rates.rates.JPY;
                context.Add(newRates);
                context.SaveChanges();
            }
        }
示例#20
0
 public async Task GetExchangeDataAsync()
 {
     foreach (var resourceUri in Dates.Select(ResourceApi.GetUri))
     {
         ExchangeRates.Add(await XmlConverter.ParseObjAsync <ExchangeRate>(resourceUri));
     }
 }
示例#21
0
        public async Task GetRates(ExchangeRates exchangeRates, Currency code)
        {
            try
            {
                int howMany = 10;
                HttpResponseMessage response = await client.GetAsync("http://api.nbp.pl/api/exchangerates/rates/a/" + code.ToString() + "/last/" + howMany.ToString() + "/?format=json");

                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    List <Rate> rateList = (JObject.Parse(responseBody)["rates"]).ToObject <List <Rate> >();
                    switch (code)
                    {
                    case Currency.usd:
                        exchangeRates.usdRates = rateList;
                        exchangeRates.usdDiff  = Math.Round((exchangeRates.usdRates[howMany - 1].mid - exchangeRates.usdRates[howMany - 2].mid) / exchangeRates.usdRates[howMany - 2].mid * 100, 3);
                        break;

                    case Currency.eur:
                        exchangeRates.eurRates = rateList;
                        exchangeRates.eurDiff  = Math.Round((exchangeRates.eurRates[howMany - 1].mid - exchangeRates.eurRates[howMany - 2].mid) / exchangeRates.eurRates[howMany - 2].mid * 100, 3);
                        break;
                    }
                }
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine("\nException Caught!");
                Console.WriteLine("Message :{0} ", e.Message);
            }
        }
示例#22
0
        public Dictionary <CurrencyPair, Task <RateResult> > FetchRates(HashSet <CurrencyPair> pairs, RateRules rules, CancellationToken cancellationToken)
        {
            if (rules == null)
            {
                throw new ArgumentNullException(nameof(rules));
            }

            var fetchingRates     = new Dictionary <CurrencyPair, Task <RateResult> >();
            var fetchingExchanges = new Dictionary <string, Task <QueryRateResult> >();
            var consolidatedRates = new ExchangeRates();

            foreach (var i in pairs.Select(p => (Pair: p, RateRule: rules.GetRuleFor(p))))
            {
                var dependentQueries = new List <Task <QueryRateResult> >();
                foreach (var requiredExchange in i.RateRule.ExchangeRates)
                {
                    if (!fetchingExchanges.TryGetValue(requiredExchange.Exchange, out var fetching))
                    {
                        fetching = _rateProviderFactory.QueryRates(requiredExchange.Exchange, cancellationToken);
                        fetchingExchanges.Add(requiredExchange.Exchange, fetching);
                    }
                    dependentQueries.Add(fetching);
                }
                fetchingRates.Add(i.Pair, GetRuleValue(dependentQueries, i.RateRule));
            }
            return(fetchingRates);
        }
示例#23
0
        public ExchangeRates Return_HMRCExchangeRates_ToModel(XDocument _xmlDoc)
        {
            List <ExchangeRate> resultList = new List <ExchangeRate>();

            foreach (XElement descendants in _xmlDoc.Root.Descendants("exchangeRate"))
            {
                string  _countryCode  = descendants.Element("countryCode").Value;
                string  _currencyCode = descendants.Element("currencyCode").Value;
                decimal _exchRate     = Convert.ToDecimal(descendants.Element("rateNew").Value);

                ExchangeRate newExchangeRate = new ExchangeRate()
                {
                    From_Country_Code  = "GB",
                    From_Currency_Code = "GBP",
                    To_Country_Code    = _countryCode,
                    To_Currency_Code   = _currencyCode,
                    Rate_of_Exchange   = _exchRate,
                };

                resultList.Add(newExchangeRate);
            }

            ExchangeRates result = new ExchangeRates()
            {
                Exchange_Rates = resultList,
                Effective_Date = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1, 0, 0, 0)
            };

            return(result);
        }
        public async Task TestAddExchangeRateIds()
        {
            var currenciesController = new CurrenciesController();
            var gbp = await currenciesController.GetCurrencies("GBP");

            var usd = await currenciesController.GetCurrencies("USD");

            if (gbp.Value == null || usd.Value == null)
            {
                Assert.Fail();
            }

            var exchangeRateToSend = new ExchangeRates {
                BaseCurrecncy     = gbp.Value.Id,
                ConvertedCurrency = usd.Value.Id,
                ExchangeRate      = 1
            };
            await exchangeRateController.AddExchangeRate(exchangeRateToSend);

            var exchangeRate = await exchangeRateController.GetExchangeRate(gbp.Value.Id, usd.Value.Id);

            if (exchangeRate.Value != null && exchangeRate.Value == exchangeRateToSend)
            {
                Assert.Pass();
            }
            else
            {
                Assert.Fail();
            }
        }
示例#25
0
        public async Task <ExchangeRates> GetRatesAsync()
        {
            var response = await _Client.GetAsync($"https://api.quadrigacx.com/v2/ticker?book=all");

            response.EnsureSuccessStatusCode();
            var rates = JObject.Parse(await response.Content.ReadAsStringAsync());

            var exchangeRates = new ExchangeRates();

            foreach (var prop in rates.Properties())
            {
                var rate = new ExchangeRate();
                if (!Rating.CurrencyPair.TryParse(prop.Name, out var pair))
                {
                    continue;
                }
                rate.CurrencyPair = pair;
                rate.Exchange     = QuadrigacxName;
                if (!TryToBidAsk((JObject)prop.Value, out var v))
                {
                    continue;
                }
                rate.BidAsk = v;
                exchangeRates.Add(rate);
            }
            return(exchangeRates);
        }
示例#26
0
        /*
         * GetWalletBalance();
         * Thread.Sleep(1000);
         * Console.Clear();
         *
         * UsdToBitcoin(2);
         *
         * GetExchangeRates(2);
         *
         * GetWalletDetails("1DW29NUoat7ayGpj6Gm45i5BxCxYfm8oD8", true);
         *
         * GetTransactionDetails("2bcdd3a51df57a5967dca3450a8f860ff5e9944b28465d31070683cc3ea60299");
         *
         * GetWalletBalance();
         * SendMoney();
         * GetWalletBalance();
         *
         * Console.ReadLine();
         * }
         *
         * private static void GetWalletBalance()
         * {
         * Wallet wallet = new Wallet("9610d5cc-e92c-469b-b83a-38b7a538a518", "Hackathon2015");
         * Console.WriteLine("Your wallet balance is: " + (double)wallet.GetBalance() / 100000000 + " BTC or " + BitcoinToUsd((double)wallet.GetBalance() / 100000000) + " USD");
         * }
         *
         * private static void SendMoney()
         * {
         * Wallet wallet = new Wallet("9610d5cc-e92c-469b-b83a-38b7a538a518", "Hackathon2015");
         * Console.WriteLine("Please enter the transaction total in USD");
         * double transactionTotal = 0.00;
         * transactionTotal = Console.Read();
         * PaymentResponse payment = wallet.Send("12j5AWTyFAicifNXbgNNti6DXNS46vC7TG",
         *      2000000, fee: 500000L, note: "Test");
         * Console.WriteLine("The payment TX hash is {0}", payment.TxHash);
         * }
         *
         * private static void GetTransactionDetails(string transactionId)
         * {
         * var explorer = new BlockExplorer();
         * Transaction trns = explorer.GetTransaction(transactionId);
         * Console.WriteLine("********* TRANSACTION DETAILS *********");
         * Console.WriteLine("Transaction ID: " + trns.Hash);
         *
         * foreach (Output o in trns.Outputs)
         * {
         *  Console.WriteLine("BTC Spent : " + (double) o.Value / 100000000);
         * }
         *
         * Console.WriteLine("Included in block: " + trns.BlockHeight);
         * Console.WriteLine("Is it double spent? " + trns.DoubleSpend);
         * long unixDate = trns.Time;
         * DateTime start = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
         * DateTime date = start.AddSeconds(unixDate).ToLocalTime();
         * Console.WriteLine("Transaction time: " + date);
         * Console.WriteLine("");
         * }
         *
         * private static void GetWalletDetails(string walletID, bool includeTransactions)
         * {
         * var explorer = new BlockExplorer();
         * Address address = explorer.GetAddress(walletID);
         * double balance = address.FinalBalance;
         * balance = balance/100000000;
         * Console.WriteLine("********* WALLET DETAILS *********");
         * Console.WriteLine("Wallet ID: " + address.AddressStr);
         * Console.WriteLine("Balance of address is: " + balance + " BTN");
         * Console.WriteLine("");
         *
         * if (includeTransactions)
         * {
         *  foreach (Transaction transaction in address.Transactions)
         *  {
         *      GetTransactionDetails(transaction.Hash);
         *  }
         *  Console.WriteLine("");
         * }
         *
         * }
         *
         * private static void GetExchangeRates(double bitcoins)
         * {
         * Dictionary<string,Currency> exchangerates = ExchangeRates.GetTicker();
         * foreach (var currency in exchangerates)
         * {
         *  Console.Write(bitcoins + " BTC = ");
         *  Console.WriteLine(currency.Value.Last*bitcoins + " " + currency.Key);
         * }
         * }
         */
        private static void UsdToBitcoin(double usd)
        {
            Dictionary <string, Currency> exchangerates = ExchangeRates.GetTicker();
            double exchangeRate = 1 / exchangerates["USD"].Last;

            Console.WriteLine(usd + " USD is = " + exchangeRate * usd + " BTC  is this ok? (y/n)");
        }
        async Task <Response> LoadRates(ExchangeRates exchangeRates, ExchangeNames exchangeNames)
        {
            // Get values
            var rateValues = new List <RateValue>();
            var type       = typeof(Rates);
            var properties = type.GetRuntimeFields();

            foreach (var property in properties)
            {
                var code = property.Name.Substring(1, 3);
                rateValues.Add(new RateValue
                {
                    Code    = code,
                    TaxRate = (double)property.GetValue(exchangeRates.Rates),
                });
            }

            // Get names
            var rateNames = new List <RateName>();

            type       = typeof(ExchangeNames);
            properties = type.GetRuntimeFields();

            foreach (var property in properties)
            {
                var code = property.Name.Substring(1, 3);
                rateNames.Add(new RateName
                {
                    Code = code,
                    Name = (string)property.GetValue(exchangeNames),
                });
            }

            // Join the complete list
            var qry = (from v in rateValues
                       join n in rateNames on v.Code equals n.Code
                       select new { v, n }).ToList();

            var rates = new List <Rate>();

            foreach (var item in qry)
            {
                rates.Add(new Rate
                {
                    Code    = item.v.Code,
                    Name    = item.n.Name,
                    TaxRate = item.v.TaxRate,
                });
            }

            await SaveData(rates);

            return(new Response
            {
                IsSuccess = true,
                Message = "Ok",
                Result = rates,
            });
        }
示例#28
0
        public void ExchangeRatesConstructorOK()
        {
            //Arrange
            ExchangeRates rates = new ExchangeRates();

            //Assert
            Assert.NotNull(rates);
        }
示例#29
0
        static void Main(string[] args)
        {
            WebConnect    web = new WebConnect();
            ExchangeRates r   = web.GetExchangeRates();

            Console.WriteLine(r);
            Console.ReadKey();
        }
        public void Ctor_EmptyErrorMessage_Test()
        {
            // Arrange
            var exchangeRates = new ExchangeRates(Mock.Of<ISessionFactory>(), Mock.Of<IRateRepository>(),
                Mock.Of<IRateService>());

            // Assert
            Assert.IsEmpty(exchangeRates.ErrorMessage);
        }
示例#31
0
 public override void Cleanup()
 {
     ExchangeRateDetail = null;
     if (ExchangeRates != null)
     {
         ExchangeRates.Cleanup();
     }
     base.Cleanup();
 }
示例#32
0
        public ActionResult ExchangeRates()
        {
            ExchangeRates USDExchangeRates = new ExchangeRates("USD");
            ExchangeRates EURExchangeRates = new ExchangeRates("EUR");
            ExchangeRates CNYExchangeRates = new ExchangeRates("CNY");
            ViewData["USD"] = USDExchangeRates.rate;
            ViewData["EUR"] = EURExchangeRates.rate;
            ViewData["CNY"] = CNYExchangeRates.rate;

            return View();
        }
        public void GetRates_ApplicationException_Test()
        {
            // Arrange
            var exception = new ApplicationException();
            var sessionFacotry = new Mock<ISessionFactory>();
            sessionFacotry.Setup(t => t.New()).Throws(exception);
            var repository = Mock.Of<IRateRepository>();
            var service = Mock.Of<IRateService>();
            var exchangeRates = new ExchangeRates(sessionFacotry.Object, repository, service);

            // Assert
            var ex = Assert.Throws<ApplicationException>(() => exchangeRates.GetRates(Currency.RUB, DateTime.Today.AddDays(-1), DateTime.Today));
            Assert.AreEqual(ex, exception);
        }
        public void DisposeSessionTest()
        {
            // Arrange
            var session = new Mock<ISession>();
            var sessionFacotry = Mock.Of<ISessionFactory>(t => t.New() == session.Object);
            var repository =
                Mock.Of<IRateRepository>(
                    t =>
                        t.GetCached(session.Object, It.IsAny<Currency>(), It.IsAny<DateTime>(), It.IsAny<DateTime>()) == new Rate[0]);
            var service =
                Mock.Of<IRateService>(
                    t => t.GetRates(Currency.RUB, It.IsAny<IEnumerable<DateTime>>()) == new Rate[0]);
            var exchangeRates = new ExchangeRates(sessionFacotry, repository, service);

            // Act
            exchangeRates.GetRates(Currency.RUB, DateTime.Today, DateTime.Today);

            // Assert
            session.Verify(t => t.Dispose(), Times.Once);
        }
示例#35
0
    public static void Main(string[] args)
    {
        // Initializing the API
        var api = new ExchangeRates("<API KEY>");

        // Example of listing currencies

        Console.WriteLine("\n********** Listing Currencies:");
        var responseCurrencies = api.GetCurrencies();

        if (responseCurrencies.IsSuccessful)
        {
            foreach (var currency in responseCurrencies.Currencies)
            {
                Console.WriteLine("{0}:{1}", currency.Code, currency.Description);
            }
        }
        else
        {
            Console.WriteLine("There was an error with the request: {0}", responseCurrencies.ErrorMessage);
        }

        // Example of checking RemainingQuotes

        var responseRemaingQuotes = api.GetRemainingQuotes();

        Console.WriteLine("\n********** Remaining Quotes:");
        if (responseRemaingQuotes.IsSuccessful)
        {
            Console.WriteLine("Remaining quotes: {0}", responseRemaingQuotes.RemainingQuotes);
        }
        else
        {
            Console.WriteLine("There was an error with the request: {0}", responseRemaingQuotes.ErrorMessage);
        }

        // Example of retrieving rates by specifying multiple fields.

        var responseGetRatesWithFields = api.GetRates("USD",
                quote: "EUR",
                start: "2014-01-01",
                end: "2014-01-05",
                fields: new List<ExchangeRates.RatesFields> { ExchangeRates.RatesFields.Averages,
                                                              ExchangeRates.RatesFields.Midpoint });

        if (responseGetRatesWithFields.IsSuccessful)
        {
            Console.WriteLine("\n********** Rates - Averages and Midpoints:");
            foreach (var quote in responseGetRatesWithFields.Quotes)
            {
                Console.WriteLine("From {0} to {1}\nQuote:{2} Ask:{3,10} MidPoint:{4,10} Bid:{5,10}",
                        responseGetRatesWithFields.Meta.EffectiveParams.StartDate.Value.ToShortDateString(),
                        responseGetRatesWithFields.Meta.EffectiveParams.EndDate.Value.ToShortDateString(),
                        quote.Key,
                        quote.Value.Ask,
                        quote.Value.Midpoint,
                        quote.Value.Bid);

            }
        }
        else
        {
            Console.WriteLine("There was an error with the request: {0}", responseGetRatesWithFields.ErrorMessage);
        }

        // Example of retrieving rates by specifying multiple quotes.

        var responseGetRatesForSeveralQuotes = api.GetRates("USD",
                quote: new List<string> {"EUR", "CHF"} ,
                date: "2014-01-01",
                fields: ExchangeRates.RatesFields.Averages);

        if (responseGetRatesForSeveralQuotes.IsSuccessful)
        {
            Console.WriteLine("\n********** Rates for USD/EUR and USD/CHF:");
            foreach (var quote in responseGetRatesForSeveralQuotes.Quotes)
            {
                Console.WriteLine("{0} Quote:{1} Ask:{2,10} Bid:{3,10}",
                        quote.Value.Date,
                        quote.Key,
                        quote.Value.Ask,
                        quote.Value.Bid);

            }
        }
        else
        {
            Console.WriteLine("There was an error with the request: {0}", responseGetRatesWithFields.ErrorMessage);
        }

        Console.ReadKey();
    }
示例#36
0
 public void Init()
 {
     exchangeRates = new ExchangeRates();
     AddActionClassesToList(exchangeRates);
 }
        public void GetRates_CacheNotEnough_Test()
        {
            // Arrange
            var session = Mock.Of<ISession>();
            var sessionFacotry = Mock.Of<ISessionFactory>(t => t.New() == session);
            var rate1 = Mock.Of<Rate>(t => t.Stamp == DateTime.Today.AddDays(-2));
            var rate2 = Mock.Of<Rate>(t => t.Stamp == DateTime.Today.AddDays(-1));
            var rate3 = Mock.Of<Rate>(t => t.Stamp == DateTime.Today);
            var repository =
                Mock.Of<IRateRepository>(
                    t =>
                        t.GetCached(session, It.IsAny<Currency>(), DateTime.Today.AddDays(-2), DateTime.Today) == new[] { rate1, rate3 });
            var service = Mock.Of<IRateService>(t => t.GetRates(Currency.RUB, It.Is<IEnumerable<DateTime>>(e => e.Single() == DateTime.Today.AddDays(-1))) == new[] { rate2});
            var exchangeRates = new ExchangeRates(sessionFacotry, repository, service);

            // Act
            var rates = exchangeRates.GetRates(Currency.RUB, DateTime.Today.AddDays(-2), DateTime.Today);

            // Assert
            Assert.AreEqual(rates[0], rate1);
            Assert.AreEqual(rates[1], rate2);
            Assert.AreEqual(rates[2], rate3);
        }
        public void GetRates_EmprtyCache_CacheRates_Test()
        {
            // Arrange
            var session = Mock.Of<ISession>();
            var sessionFacotry = Mock.Of<ISessionFactory>(t => t.New() == session);
            var repository =
                new Mock<IRateRepository>();
            repository.Setup(t => t.GetCached(session, It.IsAny<Currency>(), It.IsAny<DateTime>(), It.IsAny<DateTime>())).Returns(new Rate[0]);
            var rate = Mock.Of<Rate>();
            var service =
                Mock.Of<IRateService>(
                    t => t.GetRates(Currency.RUB, It.Is<IEnumerable<DateTime>>(e => e.Contains(DateTime.Today.AddDays(-1)) && e.Contains(DateTime.Today))) == new[] { rate });
            var exchangeRates = new ExchangeRates(sessionFacotry, repository.Object, service);

            // Act
            exchangeRates.GetRates(Currency.RUB, DateTime.Today.AddDays(-1), DateTime.Today);

            // Assert
            repository.Verify(t => t.Cache(session, It.Is<IEnumerable<Rate>>(e => e.Single() == rate)));
        }
        public void GetRates_EmprtyCache_Test()
        {
            // Arrange
            var session = Mock.Of<ISession>();
            var sessionFacotry = Mock.Of<ISessionFactory>(t => t.New() == session);
            var repository =
                Mock.Of<IRateRepository>(
                    t =>
                        t.GetCached(session, It.IsAny<Currency>(), It.IsAny<DateTime>(), It.IsAny<DateTime>()) == new Rate[0]);
            var rate = Mock.Of<Rate>();
            var service =
                Mock.Of<IRateService>(
                    t => t.GetRates(Currency.RUB, It.Is<IEnumerable<DateTime>>(e => e.Contains(DateTime.Today.AddDays(-1)) && e.Contains(DateTime.Today))) == new[] { rate });
            var exchangeRates = new ExchangeRates(sessionFacotry, repository, service);

            // Act
            var rates = exchangeRates.GetRates(Currency.RUB, DateTime.Today.AddDays(-1), DateTime.Today);

            // Assert
            Assert.AreEqual(rates.Single(), rate);
        }
        public void GetRates_EndDateIsLaterThanToday_Test()
        {
            // Arrange
            var sessionFacotry = Mock.Of<ISessionFactory>();
            var repository = Mock.Of<IRateRepository>();
            var service = Mock.Of<IRateService>();
            var exchangeRates = new ExchangeRates(sessionFacotry, repository, service);

            // Assert
            Assert.Throws<EndDateIsLaterThanTodayException>(() => exchangeRates.GetRates(Currency.RUB, DateTime.Today, DateTime.Today.AddDays(1)));
        }
        public void GetRate_ProvideErrorMessage_WhenRepositoryGetCachedFails_Test()
        {
            // Arrange
            var exception = Mock.Of<Exception>(t => t.Message == "Error message");
            var session = Mock.Of<ISession>();
            var sessionFacotry = Mock.Of<ISessionFactory>(t => t.New() == session);
            var repository = new Mock<IRateRepository>();
            repository.Setup(t => t.GetCached(It.IsAny<ISession>(), It.IsAny<Currency>(), It.IsAny<DateTime>(), It.IsAny<DateTime>()))
                      .Throws(exception);
            var service =
                Mock.Of<IRateService>(
                    t => t.GetRates(Currency.RUB, It.Is<IEnumerable<DateTime>>(e => e.Contains(DateTime.Today.AddDays(-1)) && e.Contains(DateTime.Today))) == new Rate[0]);
            var exchangeRates = new ExchangeRates(sessionFacotry, repository.Object, service);

            // Act
            exchangeRates.GetRates(Currency.RUB, DateTime.Today.AddDays(-1), DateTime.Today);

            // Assert
            Assert.AreEqual(exchangeRates.ErrorMessage, "Error message");
        }
        public void GetRates_CacheIsEnough_Test()
        {
            // Arrange
            var session = Mock.Of<ISession>();
            var sessionFacotry = Mock.Of<ISessionFactory>(t => t.New() == session);
            var rate1 = Mock.Of<Rate>(t => t.Stamp == DateTime.Today.AddDays(-1));
            var rate2 = Mock.Of<Rate>(t => t.Stamp == DateTime.Today);
            var repository =
                Mock.Of<IRateRepository>(
                    t =>
                        t.GetCached(session, It.IsAny<Currency>(), DateTime.Today.AddDays(-1), DateTime.Today) == new[] { rate2, rate1 });
            var service = new Mock<IRateService>();
            var exchangeRates = new ExchangeRates(sessionFacotry, repository, service.Object);

            // Act
            var rates = exchangeRates.GetRates(Currency.RUB, DateTime.Today.AddDays(-1), DateTime.Today);

            // Assert
            Assert.AreEqual(rates.First(), rate1);
            Assert.AreEqual(rates.Last(), rate2);
            service.Verify(t => t.GetRates(It.IsAny<Currency>(), It.IsAny<IEnumerable<DateTime>>()), Times.Never);
        }
        public void GetRates_SelectedPeriodExceedTwoMonths_Test()
        {
            // Arrange
            var sessionFacotry = Mock.Of<ISessionFactory>();
            var repository = Mock.Of<IRateRepository>();
            var service = Mock.Of<IRateService>();
            var exchangeRates = new ExchangeRates(sessionFacotry, repository, service);

            // Assert
            Assert.Throws<SelectedPeriodExceedTwoMonthsException>(() => exchangeRates.GetRates(Currency.RUB, DateTime.Today.AddDays(-100), DateTime.Today));
        }
        public void GetRate_NotThrows_WhenRepositoryGetCachedFails_Test()
        {
            // Arrange
            var session = Mock.Of<ISession>();
            var sessionFacotry = Mock.Of<ISessionFactory>(t => t.New() == session);
            var repository = new Mock<IRateRepository>();
            repository.Setup(t => t.GetCached(It.IsAny<ISession>(), It.IsAny<Currency>(), It.IsAny<DateTime>(), It.IsAny<DateTime>()))
                      .Throws<Exception>();
            var rate = Mock.Of<Rate>();
            var service =
                Mock.Of<IRateService>(
                    t => t.GetRates(Currency.RUB, It.Is<IEnumerable<DateTime>>(e => e.Contains(DateTime.Today.AddDays(-1)) && e.Contains(DateTime.Today))) == new[] { rate });
            var exchangeRates = new ExchangeRates(sessionFacotry, repository.Object, service);

            // Act
            var rates = exchangeRates.GetRates(Currency.RUB, DateTime.Today.AddDays(-1), DateTime.Today);

            // Assert
            Assert.AreEqual(rates.Single(), rate);
        }