Example #1
0
        public ActionsProviderTest()
        {
            CurrencyConverter.ClearRates();
            CurrencyConverter.One(Dollars).Costs(60.Rubles());

            _provider = new ActionsProvider();
        }
Example #2
0
        /// <summary>
        /// Entry point of the command-line utility.
        /// </summary>
        /// <param name="args">Command line arguments.</param>
        /// <returns>A <see cref="Task"/> representing the result of the asynchronous operation.</returns>
        public static async Task Main(string[] args)
        {
            using Parser parser = new Parser(with =>
            {
                with.CaseSensitive             = false;
                with.CaseInsensitiveEnumValues = true;
                with.EnableDashDash            = true;
                with.HelpWriter = Console.Out;
            });

            Options options = null;

            parser.ParseArguments <Options>(args)
            .WithParsed(opts => options = opts)
            .WithNotParsed(errors => Environment.Exit(ErrorBadArguments));

            Dictionary <Currency, decimal> exchangeRates = new Dictionary <Currency, decimal>
            {
                { Currency.EUR, (decimal)options.ExchangeRate },
                { Currency.USD, 1M }
            };

            ICurrencyConverter   currencyConverter = new CurrencyConverter(exchangeRates);
            IRecordInputService  inputService      = new CsvRecordInputService(options.InputFilePath);
            IRecordOutputService outputService     = new CsvRecordOutputService(options.OutpuFilePath);

            List <Record> records = inputService.GetRecords().Where(r => r.Price > (decimal)options.PricePoint).ToList();

            records.ForEach(r => r.Price = currencyConverter.Exchange(r.Price, Currency.EUR));

            await outputService.SetRecords(records);
        }
Example #3
0
        public void ConverterTest()
        {
            CurrencyConverter cvt   = CurrencyConverter.Instance;
            decimal           value = 100m;

            Assert.AreEqual(cvt.ConvertToEuro(cvt.ConvertFromEuro(value, "USD"), "USD"), value);
        }
Example #4
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Get our button from the layout resource,
            // and attach an event to it
            Button   button         = FindViewById <Button>(Resource.Id.myButton);
            EditText amountEditText = FindViewById <EditText>(Resource.Id.editTextAmount);
            TextView resultTextView = FindViewById <TextView>(Resource.Id.textViewResult);

            button.Click += delegate {
                var input = amountEditText.Text;
                try {
                    var conversion = CurrencyConverter.ConvertDollarsToPunds(input);
                    resultTextView.Text = StringLib.DollarToPunds(input, conversion);
                } catch (FormatException fe) {
                    // Show error message
                    Toast.MakeText(this, StringLib.CONVERSION_ERROR_MESSAGE, ToastLength.Short).Show();
                    Console.WriteLine(fe);
                }
            };
        }
Example #5
0
        public async Task <GetTotalResponseDTO> GetTotal(string amount, DeliveryType deliveryType)
        {
            var client = _httpClientFactory.CreateClient(Constants.ClientWithToken);

            var price = CurrencyConverter.currencyToDecimal(amount);

            var response2 = await client.GetAsync <decimal>(string.Format(Constants.Routes.CalculateVAT, price));

            var vat = response2.Object;

            decimal deliveryFee = 0m;

            if (deliveryType == DeliveryType.HomeDelivery)
            {
                deliveryFee = 50000;
            }

            decimal Total = price + vat + deliveryFee;

            return(new GetTotalResponseDTO
            {
                deliveryCharge = CurrencyConverter.formatAmount(deliveryFee),
                amount = CurrencyConverter.formatAmount(price),
                total = CurrencyConverter.formatAmount(Total),
                vat = CurrencyConverter.formatAmount(vat)
            });
        }
Example #6
0
        public async Task <CarsDTO> GetCarPrice(int id)
        {
            var client   = _httpClientFactory.CreateClient(Constants.ClientWithToken);
            var response = await client.GetAsync <CarsDTO>(string.Format(Constants.Routes.GetCarById, id));

            var price = response.Object.RetailPrice.GetValueOrDefault();

            //get vat
            var response2 = await client.GetAsync <decimal>(string.Format(Constants.Routes.CalculateVAT, price));

            var vat = response2.Object;

            var total = price + vat;

            var totalstring = CurrencyConverter.formatAmount(total);
            var pricestring = CurrencyConverter.formatAmount(price);
            var VatString   = CurrencyConverter.formatAmount(vat);

            var model = new CarsDTO
            {
                TotalToPay = totalstring,
                Amount     = pricestring,
                VAT        = VatString
            };

            return(model);
        }
Example #7
0
        public void CanChange_Attached_SubTransaction()
        {
            Account     Account     = TestBudget.Budget.Accounts[0];
            Transaction transaction = new Transaction();

            transaction.Amount = 100;
            transaction.MakeSplitTransaction();
            Account.Transactions.Add(transaction);

            var subTransaction = transaction.SubTransactions.Create();

            subTransaction.Amount = 50;

            var subTransaction2 = transaction.SubTransactions.Create();

            subTransaction2.Amount = 50;

            TestBudget.BudgetModel.SaveChanges();
            TestBudget.ClearEvents();

            subTransaction.Amount = 100;

            TestBudget.BudgetModel.SaveChanges();

            Assert.That(TestBudget.TestEvents, Has.Count.EqualTo(1));
            Assert.That(TestBudget.TestEvents[0], Is.TypeOf <GroupedFieldChangeEvent>());

            GroupedFieldChangeEvent groupedFieldChangeEvent = (GroupedFieldChangeEvent)TestBudget.TestEvents[0];

            Assert.That(groupedFieldChangeEvent.GroupedEvents, Has.Count.EqualTo(1));
            Assert.That(groupedFieldChangeEvent.GroupedEvents[0].EntityType, Is.EqualTo(nameof(SubTransaction)));
            var change = groupedFieldChangeEvent.GroupedEvents[0].Changes[nameof(SubTransaction.Amount)];

            Assert.That(change.NewValue, Is.EqualTo(CurrencyConverter.ToLongValue(100M, subTransaction.GetCurrencyDenominator())));
        }
Example #8
0
        /// <summary>
        /// Init ethereum transaction.
        /// </summary>
        /// <param name="trx">Transaction data model.</param>
        /// <param name="model">Transaction view model.</param>
        private async Task InitializationEthereum(Transaction trx, TransactionViewModel model)
        {
            var merchant = await _merchantRepository.GetByUser(trx.UserId);

            if (string.IsNullOrWhiteSpace(trx.Address) && !string.IsNullOrWhiteSpace(trx.XPubKey))
            {
                var account = await this._ethereumService.CreateAddress(trx.EtherId);

                trx.Address    = account.Item1;
                trx.PassPhrase = account.Item2;

                var foundsWithdraw = MAD.Withdraw(trx.Amount);
                var foundsDeposit  = MAD.Deposit(trx.Amount);

                var estimateGasSize = await _ethereumService.EstimateGasSize(trx.EtherId, merchant.EthereumAddress, trx.XPubKey, foundsWithdraw.Item1, foundsWithdraw.Item2, foundsDeposit.Item1,
                                                                             trx.Address, trx.PassPhrase);

                trx.Fee = CurrencyConverter.WeiToEther(estimateGasSize.Value);

                await this._transactionRepository.Update(trx);
            }

            if (!string.IsNullOrWhiteSpace(trx.Address))
            {
                model.ABI     = this._ethereumService.GetABI();
                model.Balance = CurrencyConverter.WeiToEther((await this._ethereumService.GetBalance(trx.Address)).Value).ToString();
            }

            model.BuyerAddress = trx.XPubKey;
            model.FeeAddress   = trx.Address;
            model.FeeValue     = trx.Fee.ToString();
        }
Example #9
0
 void CreateInstance()
 {
     if (instance == null)
     {
         instance = this;
     }
 }
Example #10
0
    /// <summary>
    /// Page load.
    /// </summary>
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!StopProcessing)
        {
            if (AuthenticationHelper.IsAuthenticated())
            {
                // Get site id of credits main currency
                int creditSiteId = ECommerceHelper.GetSiteID(SiteContext.CurrentSiteID, ECommerceSettings.USE_GLOBAL_CREDIT);

                gridCreditEvents.HideControlForZeroRows = true;
                gridCreditEvents.IsLiveSite             = IsLiveSite;
                gridCreditEvents.OnExternalDataBound   += gridCreditEvents_OnExternalDataBound;
                gridCreditEvents.OrderBy        = "EventDate DESC, EventName ASC";
                gridCreditEvents.WhereCondition = "EventCustomerID = " + CustomerId + " AND ISNULL(EventSiteID, 0) = " + creditSiteId;

                // Get total credit value
                decimal credit = (decimal)CreditEventInfoProvider.GetTotalCredit(CustomerId, SiteContext.CurrentSiteID);

                if (Currency != null)
                {
                    // Convert credit to current currency when using one
                    CurrencyConverter.TryGetExchangeRate(creditSiteId == 0, Currency.CurrencyCode, SiteContext.CurrentSiteID, ref rate);
                    credit = CurrencyConverter.ApplyExchangeRate(credit, rate);
                }

                lblCreditValue.Text = CurrencyInfoProvider.GetFormattedPrice((double)credit, Currency);
            }
            else
            {
                // Hide if user is not authenticated
                Visible = false;
            }
        }
    }
Example #11
0
        public string GetSingle([FromRoute] string product, [FromQuery] string targetCurrency)
        {
            using (var client = new WebClient())
            {
                client.DownloadFile("https://cddataexchange.blob.core.windows.net/data-exchange/htl-homework/ExchangeRates.csv", "Files/Rates.csv");
                client.DownloadFile("https://cddataexchange.blob.core.windows.net/data-exchange/htl-homework/Prices.csv", "Files/Products.csv");
            }
            string[] rate     = System.IO.File.ReadAllLines("Files/Rates.csv");
            string[] products = System.IO.File.ReadAllLines("Files/Products.csv");
            c = new CurrencyConverter(rate, products);
            List <Product> p = c.getInCurr("EUR");

            /*Console.WriteLine("asdfasdfasdf");
             * Console.WriteLine(p.Count.ToString());*/
            for (int i = 0; i < p.Count; i++)
            {
                if (p[i].name.Equals(product))
                {
                    return("{ \"price\": " + Math.Round(c.convert(targetCurrency, p[i].costEUR), 2) + " }");
                }
            }
            return(null);

            /*var rng = new Random();
             * return Enumerable.Range(1, 5).Select(index => new WeatherForecast
             * {
             *  Date = DateTime.Now.AddDays(index),
             *  TemperatureC = rng.Next(-20, 55),
             *  Summary = Summaries[rng.Next(Summaries.Length)]
             * })
             * .ToArray();*/
        }
Example #12
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Get our button from the layout resource,
            // and attach an event to it
            Button   button         = FindViewById <Button>(Resource.Id.myButton);
            EditText amountEditText = FindViewById <EditText>(Resource.Id.editTextAmount);
            TextView resultTextView = FindViewById <TextView>(Resource.Id.textViewResult);

            button.Click += delegate
            {
                var convert = new CurrencyConverter(amountEditText.Text);

                if (convert.success)
                {
                    resultTextView.Text = convert.output;
                    amountEditText.Text = "";
                }
                else
                {
                    Toast.MakeText(this, convert.errMessage, ToastLength.Long).Show();
                    amountEditText.Text = "";
                }
            };
        }
Example #13
0
        public PortfolioTest()
        {
            _prices = new Dictionary <string, Money>();

            CurrencyConverter.ClearRates();
            CurrencyConverter.One(Dollars).Costs(2.Rubles());
        }
Example #14
0
 public YahooCurrencyConverter(string baseCountryCode)
 {
     Condition.Requires(baseCountryCode, "baseCountryCode").IsNotNullOrWhiteSpace();
     _baseCountryCode   = baseCountryCode;
     _currencyConverter = new CurrencyConverter();
     _conversionRates   = new Dictionary <string, decimal>();
 }
        private bool AmountLimitsBreached(decimal amount, string currency, ProductSnapshot productData)
        {
            if (productData.MaximalAmount != null)
            {
                var maxLimitInCurrency = productData.MaximalAmount.Amount;
                if (!string.IsNullOrEmpty(currency) && !productData.MaximalAmount.Code.Equals(currency))
                {
                    var conversionMethod = _configurationService.GetEffective("offer/fee-currency-conversion-method", "Buy to middle").Result;
                    CurrencyConverter currencyConverter = new CurrencyConverter();
                    maxLimitInCurrency = currencyConverter.CurrencyConvert(productData.MaximalAmount.Amount, productData.MaximalAmount.Code, currency, DateTime.Today.ToString("o", CultureInfo.InvariantCulture), conversionMethod);
                }
                if (amount > maxLimitInCurrency)
                {
                    return(true);
                }
            }
            if (productData.MinimalAmount != null)
            {
                var minLimitInCurrency = productData.MinimalAmount.Amount;
                if (!string.IsNullOrEmpty(currency) && !productData.MinimalAmount.Code.Equals(currency))
                {
                    var conversionMethod = _configurationService.GetEffective("offer/fee-currency-conversion-method", "Buy to middle").Result;
                    CurrencyConverter currencyConverter = new CurrencyConverter();
                    minLimitInCurrency = currencyConverter.CurrencyConvert(productData.MinimalAmount.Amount, productData.MinimalAmount.Code, currency, DateTime.Today.ToString("o", CultureInfo.InvariantCulture), conversionMethod);
                }
                if (amount < minLimitInCurrency)
                {
                    return(true);
                }
            }

            return(false);
        }
 public YahooCurrencyConverter( string baseCountryCode )
 {
     Condition.Requires( baseCountryCode, "baseCountryCode" ).IsNotNullOrWhiteSpace();
     _baseCountryCode = baseCountryCode;
     _currencyConverter = new CurrencyConverter();
     _conversionRates = new Dictionary< string, decimal >();
 }
Example #17
0
        /// <summary>
        /// Downloads the API data to a List
        /// </summary>
        /// <returns></returns>
        private async Task LoadFromAPI()
        {
            try
            {
                apiConnection = new APIConnection();

                //gets data from the API
                var response = await apiConnection.GetApiData("http://restcountries.eu", "/rest/v2/all");

                //if data is unsuccessfull for some reason(internet connection problems/api down)
                if (!response.Success)
                {
                    throw new Exception(response.Answer);
                }
                //loads the result on to the Countries list
                Countries = (List <Country>)response.Result;

                response = await apiConnection.GetRates();

                CurrencyConverter.Rates = (List <Rate>)response.Result;

                CurrencyConverter.AddEuro();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Example #18
0
        static async Task Main(string[] args)
        {
            // Parse exchange rates
            var xchangeParser = new ExchangeRateParser();
            var rates         = xchangeParser.CsvToExchangeRates(
                await File.ReadAllTextAsync("ExchangeRates.csv"));

            // Parse products
            var productParser = new ProductParser();
            var products      = productParser.CsvToProducts(
                await File.ReadAllTextAsync("Prices.csv"));

            // Look for product
            var product = products.FirstOrDefault(p => p.Description == args[0]);

            if (product == null)
            {
                Console.WriteLine("Sorry, product not found");
                return;
            }

            var converter = new CurrencyConverter(rates);

            Console.WriteLine($"{converter.Convert(product.Price, product.Currency, args[1]),0:0.00}");
        }
        public void Validate_ConvertToEnglishCurrency_NegativeNumber()
        {
            string            input             = "-351";
            CurrencyConverter currencyConverter = new CurrencyConverter();

            string result = currencyConverter.ConvertToEnglishCurrency(input);
        }
Example #20
0
 private IStakingPower MapStakingPower(IStakeSettings stakeInfo, DataStakingPower stakePower, CurrencyCode currencyCode)
 {
     return(new BusinessStakingPower()
     {
         Symbol = stakeInfo.Symbol,
         Date = stakePower?.Date ?? stakeInfo.InceptionDate,
         Power = CurrencyConverter.Convert(stakePower?.Power ?? decimal.Zero, currencyCode),
         Summary = stakePower?.Summary
                   .Select(fs => new BusinessStakingPowerSummary()
         {
             Symbol = GetFunds()
                      .Single(x =>
                              x.ContractAddress.Address.Equals(fs.ContractAddress, StringComparison.OrdinalIgnoreCase))
                      .Symbol,
             Power = CurrencyConverter.Convert(fs.Power, currencyCode),
         })
                   .ToList()
                   ?? new List <BusinessStakingPowerSummary>(),
         Breakdown = stakePower?.Breakdown
                     .Select(fp => new BusinessStakingPowerFund()
         {
             Symbol = GetFunds()
                      .Single(x =>
                              x.ContractAddress.Address.Equals(fp.ContractAddress, StringComparison.OrdinalIgnoreCase))
                      .Symbol,
             FundModifier = fp.FundModifier,
             Quantity = fp.Events.Sum(x => x.Quantity),
             ModifiedQuantity = fp.Events.Sum(x => x.Quantity * x.TimeModifier * fp.FundModifier),
             Power = CurrencyConverter.Convert(fp.PricePerToken * fp.Events.Sum(x => x.Quantity * x.TimeModifier * fp.FundModifier), currencyCode),
         })
                     .ToList()
                     ?? new List <BusinessStakingPowerFund>()
     });
 }
Example #21
0
        public static void TestCurrencyConverter(string fiat, double amount)
        {
            CurrencyConverter currency = new CurrencyConverter();
            decimal           output   = currency.FiatToBTC($"{fiat}", amount);

            Console.WriteLine(output);
        }
Example #22
0
        public static List <FeeCondition> PrepareFees(List <FeeCondition> fees, string creditCurrency, string conversionMethod)
        {
            CurrencyConverter currencyConverter = new CurrencyConverter();

            foreach (FeeCondition fee in fees)
            {
                if (fee.PercentageLowerLimit.HasValue)
                {
                    if (fee.CalculatedPercentage < fee.PercentageLowerLimit.Value)
                    {
                        fee.CalculatedPercentage = fee.PercentageLowerLimit.Value;
                    }
                }
                else if (fee.PercentageUpperLimit.HasValue)
                {
                    if (fee.CalculatedPercentage > fee.PercentageUpperLimit)
                    {
                        fee.CalculatedPercentage = fee.PercentageUpperLimit.Value;
                    }
                }

                if (fee.FixedAmount != null)
                {
                    if (!fee.FixedAmount.Code.Equals(creditCurrency))
                    {
                        fee.FixedAmountInCurrency = currencyConverter.CurrencyConvert(fee.FixedAmount.Amount, fee.FixedAmount.Code, creditCurrency, DateTime.Today.ToString("o", CultureInfo.InvariantCulture), conversionMethod);
                    }
                    else
                    {
                        fee.FixedAmountInCurrency = fee.FixedAmount.Amount;
                    }
                }
            }
            return(fees);
        }
 /// <summary>
 /// Use this for initialization
 /// </summary>
 public void Awake()
 {
     if (instance == null)
     {
         instance = this;
     }
 }
        public async Task ConvertsCurrency()
        {
            // Arrange
            var grpcClientMock = TestMocks.GrpcClientMock();

            // Act
            var currencyConverter = new CurrencyConverter(grpcClientMock);

            const double expectedTotalRoi  = 750;
            const double expectedTotalFees = 75;

            var roiResult = new RoiCalculationResult()
            {
                Currency = TestConstants.BaseCurrency,
                Total    = 1000,
                Fees     = 100,
            };


            await currencyConverter.Convert(roiResult, TestConstants.BaseCurrency, TestConstants.TargetCurrency);

            // Assert
            Assert.AreEqual(roiResult.Total, expectedTotalRoi);
            Assert.AreEqual(roiResult.Fees, expectedTotalFees);
        }
Example #25
0
        public void DollarsToCents_UnknownCurrency2()
        {
            string dollars = "3";

            Assert.ThrowsException <InvalidOperationException>(
                () => CurrencyConverter.DollarsToCents(dollars));
        }
Example #26
0
        public async Task <List <FundInfo> > GetAllFunds()
        {
            List <FundInfo> fundInfo = new List <FundInfo>();

            using (var context = new InvestmentTrackerDbContext())
            {
                var                 funds             = context.FundPurchased.ToList();
                var                 fundgroups        = funds.GroupBy(x => x.SchemeCode);
                MutualFundProxy     proxy             = new MutualFundProxy();
                CurrencyConverter   currencyConverter = new CurrencyConverter();
                FundPriceCalculator calculator        = new FundPriceCalculator();
                foreach (var group in fundgroups)
                {
                    var latestPrice = await FetchLatestNavPrice(group.Key);

                    foreach (var fund in group)
                    {
                        var info = calculator.Calculate(latestPrice, fund);
                        info.IsReinvestedAmount  = fund.IsReinvestedAmount ?? false;
                        info.AmountInvestedInNZD = await currencyConverter.ConvertAsync(Currency.INR, Currency.NZD, info.AmountInvested);

                        info.CurrentValueInNZD = await currencyConverter.ConvertAsync(Currency.INR, Currency.NZD, info.CurrentValue);

                        fundInfo.Add(info);
                    }
                }
            }
            return(fundInfo);
        }
Example #27
0
    private static void ConvertTo(CurrencyConverter currencyConverter)
    {
        Console.WriteLine("Choose option:");
        Console.WriteLine("1: Convert from USD");
        Console.WriteLine("2: Convert from EUR");
        Console.WriteLine("3: Convert from RUB");

        var option = int.Parse(Console.ReadLine());

        Console.WriteLine("Enter amount");

        var input = double.Parse(Console.ReadLine());

        switch (option)
        {
        case 1:
            Console.WriteLine(currencyConverter.ConvertFromUsd(input));
            break;

        case 2:
            Console.WriteLine(currencyConverter.ConvertFromEur(input));
            break;

        case 3:
            Console.WriteLine(currencyConverter.ConvertFromRub(input));
            break;
        }
    }
 void CreateInstance()
 {
     if(instance == null)
     {
         instance = this;
     }
 }
 public TokenConverter(CurrencyConverter currencyConverter, ICurrencyService currencyService, ICoinMarketCapClient coinMarketCapClient, IFixerClient fixerClient)
 {
     this.currencyConverter   = currencyConverter;
     this.currencyService     = currencyService;
     this.coinMarketCapClient = coinMarketCapClient;
     this.fixerClient         = fixerClient;
 }
Example #30
0
        public void NormalCurrencyConversion()
        {
            //setup
            var          mock = new Mock <RateProvider>();
            RateProvider r    = mock.Object;

            //when GetRate() called with parameter ("USD","SGD") returns 1.4
            mock.Setup(x => x.GetRate("USD", "SGD")).Returns(1.4);
            CurrencyConverter c = new CurrencyConverter(r);

            //exercise
            double result = c.Convert("USD", 100, "SGD");

            //verify
            double expected = 140;

            Assert.AreEqual(expected, result);

            mock.Setup(x => x.GetRate("USD", "SGD")).Returns(1.5);
            result   = c.Convert("USD", 100, "SGD");
            expected = 150;
            Assert.AreEqual(expected, result);

            mock.Setup(x => x.GetRate("USD", "XXX")).Throws(new InvalidOperationException());
        }
Example #31
0
        public ActionResult Cart()
        {
            //if (Session["Cart"] == null)
            //{
            //    Session["Cart"] = new List<Movie>();
            //}

            //var movies = ((List<Movie>) Session["Cart"]);
            //var currencyConverter = new CurrencyConverter(Session["Currency"].ToString());
            //foreach (var movie in movies)
            //{
            //    movie.Price = currencyConverter.Convert(movie.Price);
            //}
            //return PartialView(movies);


            if (Session["Cart"] == null)
            {
                Session["Cart"] = new List <Movie>();
            }

            var movies            = new List <Movie>();
            var currencyConverter = new CurrencyConverter(Session["Currency"].ToString());

            foreach (var movie in ((List <Movie>)Session["Cart"]))
            {
                movies.Add(new Movie()
                {
                    Title       = movie.Title,
                    Price       = currencyConverter.Convert(movie.Price),
                    PicturePath = movie.PicturePath
                });
            }
            return(PartialView(movies));
        }
Example #32
0
        public static void Run([TimerTrigger("0 0 22 * * *", RunOnStartup = false)] TimerInfo myTimer, TraceWriter log)
        {
            try
            {
                Logger = new Logger(log);
                Logger.Write("Starting new process");

                StockReader  stockReader = new StockReader();
                List <Stock> stocks      = stockReader.ReadShares();

                CurrencyReader    currencyReader    = new CurrencyReader();
                List <Currency>   currencies        = currencyReader.ReadCurrencies();
                CurrencyConverter currencyConverter = new CurrencyConverter(currencies);

                PriceReader priceReader = new PriceReader(currencyConverter);
                stocks = priceReader.ReadValueOfStocks(stocks);

                DynamoWriter stockWriter = new DynamoWriter();
                stockWriter.WriteStockValues(stocks);
                stockWriter.WriteDailyTotal(stocks.Sum(x => x.TotalValue));

                Logger.Write("Process complete");
            }
            catch (Exception e)
            {
                log.Info(String.Format("Exception thrown: {0} - {1}", e.Message, e.StackTrace));
            }
        }
    public double computeTotalCost(String weight, String selectedDeliveryService, String currencyType)
    {
        double[] getWeightRate;
        double[] getRateCost;
        Boolean exist=false;
        PostageCharge DeliveryNames = null;
        CurrencyConverter cc = new CurrencyConverter(currencyTxtPath);

        foreach (PostageCharge e in this.pcEntries)
        {
            if (DeliveryNames == null)
                if (e.DeliveryService.Equals(selectedDeliveryService, System.StringComparison.OrdinalIgnoreCase))
                {
                    DeliveryNames = e;
                }
        }

        if (DeliveryNames != null)
        {
            foreach (PostageCharge e in this.pcEntries)
            {
                if (e.DeliveryService.Equals(selectedDeliveryService, System.StringComparison.OrdinalIgnoreCase))
                {
                    this.getWeightRateString = e.Weight.Split(',');
                    this.getRateCostString = e.RateCost.Split(',');
                }
            }
            getWeightRate = new double[this.getWeightRateString.Length];
            getRateCost = new double[this.getRateCostString.Length];
            for (int i = 0; i < this.getWeightRateString.Length; i++)
            {
                getWeightRate[i] = double.Parse(this.getWeightRateString[i]);
            }
            for (int i = 0; i < this.getRateCostString.Length; i++)
            {
                getRateCost[i] = double.Parse(this.getRateCostString[i]);
            }
            for (int i = 0; i < getWeightRate.Length; i++)
            {
                if (double.Parse(weight) <= getWeightRate[i])
                {
                    exist = true;
                    return cc.Convert(currentCurrencyType, double.Parse(weight) * getWeightRate[i], currencyType);
                }
            }
            if (!exist)
            {
                return cc.Convert(currentCurrencyType,
                    ((double.Parse(weight) / 100) * getWeightRate[getWeightRate.Length - 1]), currencyType);
            }
            exist = false;
        }
        return -1;
    }
    public CurrencyConverterTabPage()
    {
        this.Text = "Currency Converter";
        if (File.Exists(this.currenciesTxtPath))
        {
            cc = new CurrencyConverter(this.currenciesTxtPath);
            fromCurrency = new ComboBox();
            toCurrency = new ComboBox();
            fromLabel = new Label();
            toLabel = new Label();
            fromValue = new TextBox();
            convertBtn = new Button();

            fromLabel.Text = "Convert from";

            toLabel.Text = "To";

            fromLabel.Location = new Point(0, 30);
            toLabel.Location = new Point(150, 30);

            fromCurrency.Location = new Point(0, 50);
            toCurrency.Location = new Point(200, 50);

            fromValue.Location = new Point(0, 90);

            cc.InitComboBoxes(new ComboBox[] { fromCurrency, toCurrency });

            convertBtn.Size = new Size(70, 40);
            convertBtn.Location = new Point(129, 130);
            convertBtn.Text = "Convert";
            this.Controls.Add(convertBtn);
            convertBtn.Click += new EventHandler(convertBtn_Click);

            this.Controls.Add(fromCurrency);
            this.Controls.Add(toCurrency);
            this.Controls.Add(fromLabel);
            this.Controls.Add(toLabel);
            this.Controls.Add(fromValue);
        }
        else
        {
            Label lblError = new Label();
            lblError.Text = this.currenciesTxtPath + " is not found alongside with this program. Feature disabled.";
            lblError.Size = new Size(500, 30);
            lblError.Location = new Point(50, 130);
            this.Controls.Add(lblError);
        }
    }
Example #35
0
    private void ShowExchangeRate()
    {
        try
        {
            CurrencyConverter cc = new CurrencyConverter();

            cc.AdjustToLocalTime = false;

            // Add a proxy here is needed. Example:
            // cc.Proxy = new System.Net.WebProxy("0.0.0.0", 80);
            CurrencyData cd = cc.GetCurrencyData("SGD", "MMK");
            lbl_ExchangeRate.Text = String.Format("1 SGD = {0} Kyats", (cd.Rate - 7).ToString("C0").Replace("$", "").Replace("RM", "").Replace("¥", ""));
            lbl_checkon.Text = "based on Yahoo! Finance";
        }
        catch (Exception ex)
        {
            lbl_checkon.Text = "Service unavailable :(";
        }
    }
Example #36
0
        private double ConvertValue(double value, string currencyOrigine, string currencyDestination, int nbRetry)
        {
            if (currencyDestination == currencyOrigine)
                return value;

            try
            {

                CurrencyConverter myCurrencyConverter = new CurrencyConverter();
                CurrencyData cd = new CurrencyData(currencyOrigine, currencyDestination);
                // Creates new structure and set Base currency
                // to Euro and Target to Russian Ruble

                myCurrencyConverter.GetCurrencyData(ref cd);

                double newValue = value * cd.Rate;

                newValue = Math.Round(newValue, 2, MidpointRounding.AwayFromZero);

                return newValue;

            }
            catch (Exception ex)
            {
                if (nbRetry < ServiceParametersHelper.nbAPIRetry())
                    this.ConvertValue(value,currencyOrigine,currencyDestination, nbRetry+1);
                else
                    throw ex;
            }

            return value;
        }
Example #37
0
        private DataGridColumn GetDataGridColumn(GridItem gItem)
        {
            Binding bding = new Binding();
            if (!string.IsNullOrEmpty(gItem.PropertyName))
            {
                bding.Mode = BindingMode.TwoWay;
                bding.Path = new PropertyPath(gItem.PropertyName);
                if (gItem.ReferenceDataInfo != null)
                {
                    IValueConverter converter = CommonFunction.GetIValueConverter(gItem.ReferenceDataInfo.Type);
                    bding.Converter = converter;
                }
                else if (gItem.PropertyName.Contains("MONEY"))
                {
                    IValueConverter converter = new CurrencyConverter();
                    bding.Converter = converter;
                }
                else
                {
                    IValueConverter converter = new CommonConvert(gItem);
                    bding.Converter = converter;
                }
                
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("");
            }

            DataGridColumn dgc = null;
            switch (gItem.CType)
            {
                case ControlType.CheckBox :
                    DataGridCheckBoxColumn dgcc = new DataGridCheckBoxColumn();
                    dgcc.IsThreeState = false;
                    dgcc.Binding = bding;
                    dgc = dgcc;
                    break;
                case ControlType.Label :
                    if (gItem.ReferenceDataInfo != null)
                    {
                        DataGridReferenceColumn dgrc = new DataGridReferenceColumn();
                        dgrc.Binding = bding;
                        dgrc.DisplayMemberPath = "Text";
                        
                        dgc = dgrc;

                    }
                    else
                    {
                        DataGridTextColumn dgtc = new MyDataGridTextColumn(gItem);
                        dgtc.Binding = bding;
                        dgc = dgtc;
                    }
                    break;

                case ControlType.Combobox :

                    DataGridComboBoxColumn dgcbc = new DataGridComboBoxColumn();
                    if (gItem.ReferenceDataInfo != null)
                    {
                        IList<ITextValueItem> list = DataCore.GetRefData(gItem.ReferenceDataInfo.Type);
                        dgcbc.ItemsSource = list;
                    }
                    dgcbc.DisplayMemberPath = "Text";
                    dgcbc.Binding = bding;

                    dgc = dgcbc;
                    break;

                case ControlType.TreeViewItem :
                    DataGridIconColumn dgtvic = new DataGridIconColumn();
                    dgtvic.Binding = bding;
                    dgc = dgtvic;
                    break;
                case ControlType.Templete:
                    
                     //"<StackPanel Orientation="Horizontal"><smtx:ImageButton x:Name="myDelete" Click="Delete_Click"/></StackPanel>"
                    var gridXCs = new XElementString("StackPanel",new XAttributeString("Orientation", "Horizontal"));
                  
                    DataGridTemplateColumn dtc = new DataGridTemplateColumn();
                    dtc.CellTemplate = DataTemplateHelper.GetDataTemplate(gridXCs);
                    dgc = dtc;
                    break;
            }

            return dgc;
        }