public ActionResult EditCurrency(int?id, string code, string name, string name_lat, int order_index)
        {
            CurrencyContext context = new CurrencyContext();

            if (id != null && id > 0)
            {
                Currency currency = context.Currency.Single(cur => cur.id == id);

                currency.code        = code;
                currency.name        = name;
                currency.name_lat    = name_lat;
                currency.order_index = order_index;

                context.SaveChanges();
            }
            else
            {
                Currency currency = new Currency
                {
                    code        = code,
                    name        = name,
                    name_lat    = name_lat,
                    order_index = order_index,
                };

                context.Currency.Add(currency);
                context.SaveChanges();
            }

            return(RedirectToAction("Index"));
        }
        public ActionResult EditCourse(int?id, double buy, double sell)
        {
            CurrencyContext context = new CurrencyContext();
            Courses         course  = context.Courses.FirstOrDefault(cor => cor.currency_id == id);

            if (course != null)
            {
                course.buy  = buy;
                course.sell = sell;

                context.SaveChanges();
            }
            else
            {
                course = new Courses
                {
                    currency_id = (int)id,
                    buy         = buy,
                    sell        = sell,
                };

                context.Courses.Add(course);
                context.SaveChanges();
            }

            return(RedirectToAction("Index"));
        }
        private async Task <double> populateDbRatesFromHNB(string currency, DateTime rateDate)
        {
            var    formatedDate = rateDate.ToString("yyyy-MM-dd");
            string responseBody = "";

            try
            {
                HttpResponseMessage response = await client.GetAsync($"http://api.hnb.hr/tecajn/v2?valuta={currency}&datum-primjene={formatedDate}");

                response.EnsureSuccessStatusCode();
                responseBody = await response.Content.ReadAsStringAsync();
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine("\nException Caught!");
                Console.WriteLine("Message :{0} ", e.Message);
            }

            var rateString = JsonConvert.DeserializeObject <CurrencyInfo[]>(responseBody).FirstOrDefault()?.RateString;

            double rate = double.Parse(rateString.Replace(',', '.'));

            Currency selectedCurrency = context.Currencies.Where(c => c.Name == currency).FirstOrDefault();

            context.Rates.Add(
                new RateByDate
            {
                Currency = selectedCurrency,
                Date     = rateDate,
                Rate     = rate
            });

            context.SaveChanges();
            return(rate);
        }
Exemple #4
0
        public bool AddCurrency(Currency currency)
        {
            int count = 0;

            try
            {
                currencyContext.Currencies.Add(currency);
                count = currencyContext.SaveChanges();
            }
            catch (Exception ex)
            {
                logger.Error(ex.InnerException);
            }
            return(count != 0);
        }
Exemple #5
0
        public void EnsurFiatSeedData(string filePath)
        {
            CurrencyContext currencyContext = new CurrencyContext();

            if (!currencyContext.Fiat.Any())
            {
                dynamic jsonData = ReadJsonFile(filePath);
                if (jsonData != null)
                {
                    foreach (dynamic d in jsonData)
                    {
                        currencyContext.Fiat.Add(new FiatEntity()
                        {
                            Id          = d.Id,
                            Code        = d.Code,
                            Description = d.Description,
                            Name        = d.Name,
                            Symbol      = d.Symbol,
                            DisplayName = d.DisplayName,
                            FlagId      = d.FlagId,
                            ImageId     = d.ImageId
                        });
                    }
                    currencyContext.SaveChanges();
                }
            }
        }
Exemple #6
0
        public static void RestToDB(DateTime someDaysAgo)
        {
            var    client  = new RestClient(@"http://data.fixer.io/api/");
            string key     = "96067c8c5fb4cd025c5edec854c44316";
            var    request = new RestRequest(MakeResponceFixer_io(key, someDaysAgo), Method.GET);

            request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
            var queryResult = client.Execute(request);

            if (queryResult.StatusCode == HttpStatusCode.OK)

            {
                string  rawResponse  = queryResult.Content;
                JObject jsonResponce = JObject.Parse(rawResponse);
                //using (StreamWriter file = File.CreateText(@"C:\1\currency.json"))
                //using (JsonTextWriter writer = new JsonTextWriter(file))
                //{
                //    jsonResponce.WriteTo(writer);
                //}


                using (CurrencyContext db = new CurrencyContext())
                {
                    Currency currencyRate = JsonConvert.DeserializeObject <Currency>(rawResponse);

                    var dt = currencyRate.Date;
                    Console.WriteLine("Add infofmation for date -- " + dt);

                    db.Currencies.Add(currencyRate);
                    db.SaveChanges();
                }
            }
        }
Exemple #7
0
        public Rate AddRate(Rate rate)
        {
            using (CurrencyContext dbContext = new CurrencyContext())
            {
                var dateToUse = GetDate(rate, dbContext);

                var currencyToUse = GetCurrency(rate, dbContext);

                Rate dbRate = dbContext.Rates.AsEnumerable().FirstOrDefault(r => r.Currency == currencyToUse &&
                                                                            r.Date == dateToUse);
                if (dbRate != null)
                {
                    return(dbRate);
                }


                var newRate = dbContext.Rates.Add(new Rate
                {
                    Price       = rate.Price,
                    Currency    = currencyToUse,
                    Date        = dateToUse,
                    TableNumber = rate.TableNumber
                });
                dbContext.SaveChanges();


                return(newRate);
            }
        }
Exemple #8
0
        public async Task UpdateExchange()
        {
            //get currency list  needed for publish
            string Clist = ConfigurationManager.AppSettings["CurrencyList"];

            string[] ListArray  = Clist.Split(',');
            var      Currencies = _context.CurrencyRates.ToList();

            for (int i = 0; i < ListArray.Length; i++)
            {
                var client      = new RestClient("https://www.google.com/finance/converter?a=1&from=" + ListArray[i] + "&to=INR&meta=" + Guid.NewGuid().ToString());
                var request     = new RestRequest(Method.GET);
                var queryResult = client.Execute(request);
                //[^<]+
                var result = Regex.Matches(queryResult.Content, "<span class=\"?bld\"?>([^<]+)</span>")[0].Groups[1].Value;
                result = result.Substring(0, result.IndexOf(' '));
                var CrrencyEntity = Currencies.Find(a => a.SourceCurrency == ListArray[i]);
                if (CrrencyEntity != null)
                {
                    CrrencyEntity.UpdatedDate  = DateTime.Now;
                    CrrencyEntity.ExchangeRate = Convert.ToDecimal(result);
                }
                else
                {
                    CurrencyExchangeRates NewCrrency = new CurrencyExchangeRates();
                    NewCrrency.CreatedDate         = DateTime.Now;
                    NewCrrency.UpdatedDate         = DateTime.Now;
                    NewCrrency.ExchangeRate        = Convert.ToDecimal(result);
                    NewCrrency.DestinationCurrency = "INR";
                    NewCrrency.SourceCurrency      = ListArray[i];
                    _context.CurrencyRates.Add(NewCrrency);
                }
            }
            await Task.Run(() => _context.SaveChanges());
        }
Exemple #9
0
        private bool UpdateCurrencyData(DateTime date)
        {
            try
            {
                var      ci = CultureInfo.GetCultureInfo("ru-RU");
                Currency c;
                Rate     r;
                var      xdoc = XDocument.Load($"http://www.cbr.ru/scripts/XML_daily.asp?date_req={date.ToString("dd'/'MM'/'yyyy")}");
                foreach (var item in xdoc.Descendants("Valute").Select(x => new
                {
                    Id = x.Attribute("ID").Value,
                    Name = x.Element("Name").Value,
                    ISO = x.Element("CharCode").Value,
                    Value = decimal.Parse(x.Element("Value").Value, ci),
                    Nominal = int.Parse(x.Element("Nominal").Value),
                }))
                {
                    c = Context.Currency.SingleOrDefault(e => e.Id == item.Id);
                    if (c != null)
                    {
                        c.Name    = item.Name;
                        c.Nominal = item.Nominal;
                        c.Iso     = item.ISO;
                    }
                    else
                    {
                        Context.Currency.Add(new Currency()
                        {
                            Id      = item.Id,
                            Name    = item.Name,
                            Nominal = item.Nominal,
                            Iso     = item.ISO
                        });
                    }

                    r = Context.Rate.SingleOrDefault(e => e.CurrencyId == item.Id && e.Date == date);

                    if (r != null)
                    {
                        r.Value = item.Value;
                    }
                    else
                    {
                        Context.Rate.Add(new Rate()
                        {
                            CurrencyId = item.Id, //pk
                            Date       = date,    //pk
                            Value      = item.Value
                        });
                    }
                }
                Context.SaveChanges();
                return(true);
            }
            catch
            {
                return(false);
            }
        }
Exemple #10
0
        public void SavePrices(List <CryptoPrice> cryptoPrices)
        {
            var assetId = GetAssetId(cryptoPrices.First().BaseCurrency, cryptoPrices.First().QuoteCurrency);
            var prices  = cryptoPrices.ConvertAll(x => _modelMapper.MapToModel(x, assetId));

            _context.prices.AddRange(prices);
            _context.SaveChanges();
        }
Exemple #11
0
        public CurrencyController(CurrencyContext context)
        {
            _context = context;

            if (_context.Currency.Count() == 0)
            {
                // Create a new TodoItem if collection is empty,
                // which means you can't delete all TodoItems.
                _context.Currency.Add(new Currency {
                    Name = "RUS"
                });
                _context.SaveChanges();
            }
        }
Exemple #12
0
        public Currency GetCurrency(Rate rate, CurrencyContext dbContext)
        {
            Currency dbCurrency = dbContext.Currencies.FirstOrDefault(c => c.Name.Equals(rate.Currency.Name));

            var currencyToUse = dbCurrency ?? rate.Currency;

            if (currencyToUse.Name != rate.Currency.Name)
            {
                dbContext.Currencies.Add(currencyToUse);
                dbContext.SaveChanges();
            }

            return(currencyToUse);
        }
Exemple #13
0
        // GET: api/Rates/25-05-2018/31-05-2018

        public IHttpActionResult GetRates(int id, string dtStart, string dtEnd)
        {
            var dt1 = dtStart.Split('-');
            var dt2 = dtEnd.Split('-');

            DateTime _dtStart = new DateTime(Int32.Parse(dt1[2]), Int32.Parse(dt1[1]), Int32.Parse(dt1[0]));
            DateTime _dtEnd   = new DateTime(Int32.Parse(dt2[2]), Int32.Parse(dt2[1]), Int32.Parse(dt2[0]));;

            var result = db.Rates.Where(lq => lq.CurrencyId == id && lq.Date >= _dtStart && lq.Date <= _dtEnd).ToList();

            Connection connection = new Connection();
            Currency   c          = db.Currencies.Where(lq => lq.Id == id).FirstOrDefault();

            string file_path  = "http://www.cbr.ru/scripts/XML_valFull.asp";
            string ParentCode = connection.GetParentCode(c.Code, file_path);
            var    elements   = connection.GetRangeOfValues(ParentCode, dtStart, dtEnd, id);

            if (result != null)
            {
                db.Rates.RemoveRange(result);
            }
            if (elements != null)
            {
                db.Rates.AddRange(elements);
            }

            db.SaveChanges();
            var res = db.Rates.Where(lq => lq.CurrencyId == id && lq.Date >= _dtStart && lq.Date <= _dtEnd).ToList();

            if (res == null)
            {
                bool error = true;
                return(Json(error));
            }

            return(Json(res));
        }
        public async Task <Transaction> CurrencyPurchase(Purchase purchase)
        {
            string[] exchange = await GetExchange(purchase.Currency);

            var user        = _context.Users.Find(purchase.UserId);
            var transaction = new Transaction()
            {
                User = user, Amount = purchase.Amount, Currency = purchase.Currency
            };

            transaction.Result = purchase.Amount * Double.Parse(exchange[1]);
            _context.Add(transaction);
            _context.SaveChanges();
            return(transaction);
        }
Exemple #15
0
        public static void UpdateExchangeRate()
        {
            string currencyJsonUrl = "https://www.doviz.com/api/v1/currencies/all/latest";
            string currencyJsonSerializeList;

            using (CurrencyContext context = new CurrencyContext())
            {
                using (var webClient = new WebClient())
                {
                    currencyJsonSerializeList = webClient.DownloadString(currencyJsonUrl);
                }
                dynamic currencyDeserializeList = JsonConvert.DeserializeObject(currencyJsonSerializeList);
                context.Database.ExecuteSqlCommand("Delete From ExchangeRateData");
                foreach (var currencyDeserializeItem in currencyDeserializeList)
                {
                    ExchangeRateData exchangeRate = new Entities.Model.ExchangeRateData
                    {
                        Id           = currencyDeserializeItem.currency,
                        CurrencyCode = Iso4217CurrencyCodeList.GetCurrencyCode(currencyDeserializeItem.code.ToString()),
                        Buying       = currencyDeserializeItem.buying,
                        Selling      = currencyDeserializeItem.selling,
                        Name         = currencyDeserializeItem.name,
                        FullName     = currencyDeserializeItem.full_name,
                        ChangeRate   = currencyDeserializeItem.change_rate,
                        CreatedDate  = DateTime.Now,
                    };

                    context.ExchangeRate.Add(exchangeRate);
                    var exchangeRateHistory =
                        new ExchangeRateHistory
                    {
                        CurrencyCode = exchangeRate.CurrencyCode,
                        Buying       = exchangeRate.Buying,
                        Selling      = exchangeRate.Selling,
                        ChangeRate   = exchangeRate.ChangeRate,
                        Name         = currencyDeserializeItem.name,
                        FullName     = currencyDeserializeItem.full_name,
                        CreatedDate  = DateTime.Now
                    };
                    context.ExchangeRateHistory.Add(exchangeRateHistory);
                }
                context.SaveChanges();
            }
        }
Exemple #16
0
        public static void PopulateDatabase()
        {
            using var context = new CurrencyContext();

            context.AddRange(
                new TestEntity1
            {
                Currency = Currency.UsDollars
            },
                new TestEntity1
            {
                Currency = Currency.Euros
            },
                new TestEntity1
            {
                Currency = Currency.PoundsSterling
            },
                new TestEntity2
            {
                Currency = Currency.UsDollars
            },
                new TestEntity2
            {
                Currency = Currency.Euros
            },
                new TestEntity2
            {
                Currency = Currency.PoundsSterling
            },
                new TestEntity3
            {
                Currency = Currency.UsDollars
            },
                new TestEntity3
            {
                Currency = Currency.Euros
            },
                new TestEntity3
            {
                Currency = Currency.PoundsSterling
            });

            context.SaveChanges();
        }
Exemple #17
0
        public Date GetDate(Rate rate, CurrencyContext dbContext)
        {
            Date dbDate = dbContext.Dates.FirstOrDefault(d => d.Day == rate.Date.Day &&
                                                         d.Month == rate.Date.Month &&
                                                         d.Year == rate.Date.Year);
            var dateToUse = dbDate ?? new Date()
            {
                Day   = rate.Date.Day,
                Month = rate.Date.Month,
                Year  = rate.Date.Year
            };

            if (dateToUse != dbDate)
            {
                dbContext.Dates.Add(dateToUse);
                dbContext.SaveChanges();
            }


            return(dateToUse);
        }
Exemple #18
0
        //Метод для обновления данных в таблице
        //[Authorize]
        //[HttpPost]
        public ActionResult Update()
        {
            HttpClient http = new HttpClient();
            var        data = http.GetAsync("http://www.cbr.ru/scripts/XML_daily.asp").Result.Content.ReadAsStringAsync().Result;
            XDocument  xDoc = XDocument.Parse(data);

            List <Currency> currencyList = xDoc.Descendants("Valute").Select
                                               (currency => new Currency
            {
                name = currency.Element("Name").Value,
                rate = Convert.ToDouble(currency.Element("Value").Value)
            }).ToList();

            using (CurrencyContext currencyDb = new CurrencyContext())
            {
                foreach (var i in currencyList)
                {
                    var v = currencyDb.Currency.Where(cur => cur.name.Equals(i.name)).FirstOrDefault();

                    if (v != null)
                    {
                        v.name = i.name;
                        v.rate = i.rate;
                    }
                    else
                    {
                        currencyDb.Currency.Add(i);
                    }

                    currencyDb.SaveChanges();
                }
            }

            ViewBag.Success = "Updated successfully..";

            return(View("Index"));
        }
Exemple #19
0
        public static void Initialize(CurrencyContext context)
        {
            context.Database.EnsureCreated(); //creates tables

            if (!context.USD_AUD.Any())
            {
                context.USD_AUD.AddRange(
                    USD_AUD_Data.Get()
                    .Select(l => new USD_AUD {
                    Date = l.Date, Value = l.Value
                })
                    .ToList());
            }

            if (!context.USD_EUR.Any())
            {
                context.USD_EUR.AddRange(
                    USD_EUR_Data.Get()
                    .Select(l => new USD_EUR {
                    Date = l.Date, Value = l.Value
                })
                    .ToList());
            }

            if (!context.EUR_AUD.Any())
            {
                context.EUR_AUD.AddRange(
                    EUR_AUD_Data.Get()
                    .Select(l => new EUR_AUD {
                    Date = l.Date, Value = l.Value
                })
                    .ToList());
            }

            context.SaveChanges();
        }
Exemple #20
0
        public void EnsureSeedCurrencyData(string filePath)
        {
            CurrencyContext currencyContext = new CurrencyContext();

            if (!currencyContext.Currency.Any())
            {
                dynamic jsonData = ReadJsonFile(filePath);
                if (jsonData != null)
                {
                    foreach (dynamic d in jsonData)
                    {
                        currencyContext.Currency.Add(new CurrencyEntity()
                        {
                            Id          = d.Id,
                            Code        = d.Code,
                            Description = d.Description,
                            MarketCap   = d.MarketCap,
                            Name        = d.Name
                        });
                    }
                    currencyContext.SaveChanges();
                }
            }
        }