Exemplo n.º 1
0
        public void AddFunds(IClient client, double amount, ICurrency currency, IEmailSender emailSender, ILogger logger)
        {
            if (client.Accounts.Count > 0)
            {
                IAccount account = client.Accounts[0];
                if (!(currency is DinarCurrency))
                {
                    amount = FinanceManager.Convert(currency, amount);
                }

                if (client is IOrganization)
                {
                    if (amount < 10000)
                    {
                        logger.ErrorLogg("Amount cannot be smaller than 10000 for organizations");
                        return;
                    }
                }

                if (account.Credit != null)
                {
                    FinanceManager.CreditPayment(account.Id, amount);
                    emailSender.SendEmail("Credit debt is reduced.", client.Email);
                }
                else
                {
                    FinanceManager.AccountPayment(account.Id, amount);
                }
            }
            else
            {
                throw new Exception("This user has 0 accounts");
            }
        }
Exemplo n.º 2
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="account">User account</param>
 /// <param name="value">Initial value for this order</param>
 /// <param name="requestedCurrency">Currency that is requested</param>
 /// <param name="feeFactory">Fee factory to use for calculating transaction costs</param>
 public MonetaryOrder(IAccountTypeInternal account, Money value, ICurrency requestedCurrency, IFeeFactory feeFactory)
     : base(account, value)
 {
     this.requestedCurrency = requestedCurrency;
     checkInitialValues();
     setCommission(feeFactory);
 }
Exemplo n.º 3
0
 public Journal(JournalTypes journalType, string journalNumber, IManagementCompany managementCompany, ICurrency currency)
 {
     this.JournalType = journalType;
     this.JournalNumber = journalNumber;
     this.ManagementCompany = managementCompany;
     this.currency = Currency;
 }
Exemplo n.º 4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:B4F.TotalGiro.Instruments.Price">Price</see> class.
 /// </summary>
 /// <param name="quantity">The quantity (just a number) of the price</param>
 /// <param name="underlying">The currency the price is in</param>
 /// <param name="instrument">The instrument to which the price belongs</param>
 /// <param name="xRate">The xRate involved</param>
 public Price(Decimal quantity, ICurrency underlying, IInstrument instrument, decimal xRate)
 {
     this.quantity = quantity;
     this.underlying = underlying;
     this.instrument = instrument;
     this.xRate = xRate;
 }
Exemplo n.º 5
0
        public void SerializingValidValueWithDoubleRepresentation(
            [ValueSource(nameof(AllCurrencies))]
            ICurrency currency)
        {
            var amount = 1.23m;
            var value  = new Money(amount, currency);
            var stub   = new StubWithDoubleRepresentation()
            {
                Money = value
            };
            var doc = Serialize(stub);

            doc = doc.GetValue(_moneyField).AsBsonDocument;
            BsonValue amountValue   = null;
            BsonValue currencyValue = null;

            Assert.Multiple(() =>
            {
                Assert.DoesNotThrow(() => amountValue   = doc.GetElement(_customAmountFieldName).Value);
                Assert.DoesNotThrow(() => currencyValue = doc.GetElement(_customCurrencyFieldName).Value);
            });
            Assert.Multiple(() =>
            {
                Assert.That(amountValue.BsonType, Is.EqualTo(BsonType.Double));
                Assert.That(amountValue.AsDouble, Is.EqualTo((double)amount));
                Assert.That(currencyValue.BsonType, Is.EqualTo(BsonType.String));
                Assert.That(currencyValue.AsString, Is.EqualTo(currency.CharCode));
            });
        }
 protected override string CreateRequestUrl(double amount, ICurrency fromCurrency, ICurrency toCurrency)
 {
     return(string.Format(@"http://www.bing.com/search?q={0}+{1}+in+{2}+site%3Anowhereplace.pt&scope=web&mkt=en-US&FORM=W0LH",
                          amount,
                          fromCurrency.Name.Replace(" ", "+"),
                          toCurrency.Name.Replace(" ", "+")));
 }
Exemplo n.º 7
0
        public Change Add(ICurrency currencyType, int count = 1)
        {
            if (_currency.ContainsKey(currencyType)) count += _currency[currencyType];
            _currency[currencyType] = count;

            return this;
        }
Exemplo n.º 8
0
    protected void Button3_Click(object sender, EventArgs e)
    {
        try
        {
            //connect
            string connectMessage = Connect();

            //get base currency
            ICompany thisCompany = _session.Company.Get();
            if (thisCompany == null)
            {
                throw new Exception("No company found.");
            }

            ICurrency thisCurrency = thisCompany.BaseCurrency;
            if (thisCurrency == null)
            {
                throw new Exception("No currency found.");
            }

            TextBox4.Text += thisCurrency.Code;
        }
        catch (Exception ex)
        {
            TextBox4.Text += ex.Message;
        }
        finally
        {
            //always disconnect after we are finished.
            Disconnect();
        }
    }
Exemplo n.º 9
0
 /// <summary>
 /// Initializes Exchange object
 /// </summary>
 /// <param name="ExchangeName">Name</param>
 /// <param name="defaultCurrency">Default currency</param>
 /// <param name="defaultCountry">Default country</param>
 /// <param name="defaultSettlementPeriod">Default settlement period</param>
 public Exchange(string ExchangeName, ICurrency defaultCurrency, ICountry defaultCountry, short defaultSettlementPeriod)
 {
     this.exchangeName = ExchangeName;
     this.defaultCountry = defaultCountry;
     this.DefaultCurrency = defaultCurrency;
     this.defaultSettlementPeriod = defaultSettlementPeriod;
 }
Exemplo n.º 10
0
        /// <summary>
        /// Constructor for creating a test FeeClient object
        /// </summary>
        /// <param name="account"></param>
        /// <param name="instrument"></param>
        /// <param name="side"></param>
        /// <param name="actiontype"></param>
        /// <param name="transactionDate"></param>
        /// <param name="issizebased"></param>
        /// <param name="orderValue"></param>
        /// <param name="amount"></param>
        /// <param name="price"></param>
        /// <param name="ordercurrency"></param>
        /// <param name="isValueInclComm"></param>
        public CommClient(IAccountTypeInternal account,IInstrument instrument, Side side, OrderActionTypes actiontype, 
                         DateTime transactionDate, bool issizebased, InstrumentSize orderValue, Money amount, Price price,
                         ICurrency ordercurrency, bool isValueInclComm)
        {
            if (account == null)
                throw new ApplicationException("It is not possible to calculate the commission when the account is unknown.");

            if (instrument == null)
                throw new ApplicationException("It is not possible to calculate the commission when the instrument value is unknown.");

            this.account = account;
            this.instrument = instrument;
            this.Side = side;
            this.ActionType = actiontype;
            this.TransactionDate = transactionDate;
            this.IsSizeBased = issizebased;
            this.OriginalOrderType = issizebased ? BaseOrderTypes.SizeBased : BaseOrderTypes.AmountBased;
            this.Value = orderValue;
            this.amount = amount;
            this.Price = price;
            this.OrderCurrency = ordercurrency;
            this.IsValueInclComm = isValueInclComm;

            type = CommClientType.Test;
        }
Exemplo n.º 11
0
 public void SetModel(ICurrency currency)
 {
     this.currency         = currency;
     currencyNameText.text = currency.Name;
     balanceText.text      = currency.Balance.ToString();
     currency.AddBallanceChangeListener(OnBalanceChanged);
 }
Exemplo n.º 12
0
        public async Task <CryptonatorApiResponse> GetConversionRateAsync(ICurrency primary, ICurrency secondary)
        {
            if (primary == null || secondary == null)
            {
                throw new ArgumentNullException("You cannot specify null as currency.");
            }

            if ((primary.Type & CurrencyType.Primary) != CurrencyType.Primary)
            {
                throw new ArgumentException("Specified primary currency is not usable as primary currency.", nameof(primary));
            }

            if ((secondary.Type & CurrencyType.Secondary) != CurrencyType.Secondary)
            {
                throw new ArgumentException("Specified secondary currency is not usable as secondary currency.", nameof(primary));
            }

            var url = string.Concat("https://api.cryptonator.com/api/full/", primary.Code.ToLower(), "-", secondary.Code.ToLower());

            using (var req = new HttpRequestMessage(HttpMethod.Get, url))
            {
                var res = await this.Http.SendAsync(req);

                if (!res.IsSuccessStatusCode)
                {
                    throw new Exception("Cryptonator API returned an error.");
                }

                var resd = JsonConvert.DeserializeObject <CryptonatorApiResponse>(await res.Content.ReadAsStringAsync());
                return(resd);
            }
        }
Exemplo n.º 13
0
        public virtual ICurrency Calculate(ICurrency currency, decimal price, decimal tender)
        {
            if (currency.AllDenominations.Count == 0)
            {
                throw new InvalidCurrencyException("No currency denominations found");
            }

            decimal change = tender - price;

            // the currency.AllDenominations.Min(x => x.Denomination) is to ensure that if there is a currency that
            // has a minimum value that is less then that change, the extra will be "dropped" and no infinite loop will occur.
            // This itself has the problem that in a large system, these "dropped" percentages could be significant.  This would
            // be addressed with the business and the development team to determine the best course of action.
            while (change >= currency.AllDenominations.Min(x => x.Denomination))
            {
                foreach (Money money in currency.AllDenominations)
                {
                    while (change >= money.Denomination)
                    {
                        money.Add(1);
                        change -= money.Denomination;
                    }
                }
            }
            return(currency);
        }
Exemplo n.º 14
0
        public DataSet SelectCurrencyTest(ICurrency currency)
        {
            DataSet tableVerify = new DataSet();

            tableVerify = dbEntity.SelectObject(currency) as DataSet;
            return(tableVerify);
        }
Exemplo n.º 15
0
 public CurrencyExchangeResult(ICurrency exchangedCurrency, double exchangedAmount, DateTime timestamp, object state)
 {
     ExchangedCurrency = exchangedCurrency;
     ExchangedAmount   = exchangedAmount;
     Timestamp         = timestamp;
     State             = state;
 }
 protected override string CreateRequestUrl(double amount, ICurrency fromCurrency, ICurrency toCurrency)
 {
     return(string.Format(@"http://moneycentral.msn.com/investor/market/currencyconverter.aspx?strAmt={0}&iSelectCurFrom={1}&iSelectCurTo={2}",
                          amount,
                          ((MsnMoneyCurrency)fromCurrency).Id,
                          ((MsnMoneyCurrency)toCurrency).Id));
 }
Exemplo n.º 17
0
        private String addRateLog(ForumPost data, String content)
        {
            if (data.Rate == 0)
            {
                return(content);
            }
            List <ForumRateLog> logs = rateService.GetByPost(data.Id);
            StringBuilder       sb   = new StringBuilder();

            sb.AppendFormat("<div class=\"forum-rate-list\"><div class=\"forum-rate-title\">{0}</div>", alang("creditLog"));
            sb.Append("<table class=\"forum-rate-table table table-condensed\">");
            foreach (ForumRateLog x in logs)
            {
                ICurrency currency = currencyService.GetICurrencyById(x.CurrencyId);

                sb.Append("<tr>");
                sb.AppendFormat("<td class=\"forum-rate-user\"><a href=\"{0}\" target=\"_blank\">{1}</a></td>", toUser(x.User), x.User.Name);
                sb.AppendFormat("<td class=\"forum-rate-name\">{0} <span class=\"forum-rate-value\">+{1}</span></td>", currency.Name, x.Income);

                sb.AppendFormat("<td class=\"forum-rate-note\">{0}</td>", x.Reason);
                sb.AppendFormat("<td class=\"forum-rate-time\">{0}</td>", x.Created.ToString("g"));

                sb.Append("</tr>");
            }
            sb.Append("</table></div>");
            return(content + sb.ToString());
        }
Exemplo n.º 18
0
        public async Task <int> CreateOrder(int userid, CreateorderPayload createorderPayload)
        {
            List <Task> addticketstoorder = new List <Task>();
            var         order             = new Order();

            order.Orderitems = createorderPayload.Ordertoreserve;
            var occurrencedateintid = await WithConnection(async c =>
            {
                return(c.Query <int>("select Activity_occurrence_id from Activity_occurrence where Activity_id = @activityid and Start_datetime = @activitydate",
                                     new { activityid = createorderPayload.Activityid, @activitydate = createorderPayload.Activityoccurrencedate }, commandType: CommandType.Text).FirstOrDefault());
            });

            var orderid = await WithConnection(async c =>
            {
                DynamicParameters parameters = new DynamicParameters();
                parameters.Add("@activityoccurrenceid", occurrencedateintid, DbType.Int32);
                parameters.Add("@userid", userid, DbType.Int32);
                parameters.Add("@amount", order.Orderamount, DbType.Int32);
                parameters.Add("@output", DbType.Int32, direction: ParameterDirection.Output);
                await c.ExecuteAsync("Createorder", parameters, commandType: CommandType.StoredProcedure);
                int output = parameters.Get <int>("@output");
                return(output);
            });

            foreach (var ticket in createorderPayload.Ordertoreserve)
            {
                ICurrency currency = null;
                await new TicketRepository(_config).AddTickettoorder(occurrencedateintid, orderid, ticket.Id, ticket.Quantity);
            }
            //await Task.WhenAll(addticketstoorder);
            return(orderid);
        }
Exemplo n.º 19
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:B4F.TotalGiro.Instruments.Price">Price</see> class.
 /// </summary>
 /// <param name="money">This is the amount that one particular instrument to which the price belongs would cost</param>
 /// <param name="instrument">The instrument to which the price belongs</param>
 public Price(Money money, IInstrument instrument)
 {
     this.quantity = money.Quantity;
     this.underlying = (ICurrency)money.Underlying;
     this.instrument = instrument;
     this.XRate = money.XRate;
 }
Exemplo n.º 20
0
        public bool CanUseOnNormal(ICurrency currency)
        {
            var          item         = _factory.GetNormal();
            AffixManager affixManager = CreateAffixManager(item.ItemBase);

            return(currency.Execute(item, affixManager));
        }
Exemplo n.º 21
0
 private void ClearCurrency(ICurrency currency)
 {
     foreach (Money money in currency.AllDenominations)
     {
         money.Clear();
     }
 }
Exemplo n.º 22
0
        public async Task Update(
            ICurrency currency,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            ThrowIfDisposed();
            cancellationToken.ThrowIfCancellationRequested();
            if (currency == null)
            {
                throw new ArgumentException("currency must not be null");
            }
            if (currency.Id == Guid.Empty)
            {
                throw new ArgumentException("currency must have a non-empty id");
            }

            var c = Currency.FromICurrency(currency);

            await EnsureProjectId().ConfigureAwait(false);

            await currencyCommands.UpdateAsync(
                projectId,
                c.Id.ToString(),
                c,
                cancellationToken).ConfigureAwait(false);
        }
Exemplo n.º 23
0
        protected override void InitializeObject(IGenericEntity ent)
        {
            if (ent is ICurrency)
            {
                ICurrency         Currency = (ICurrency)ent;
                DBStoredProcedure spInsert = new DBStoredProcedure();
                spInsert.ProcedureName = "catInsertCurrency";
                spInsert.AddParameter(new DBParameter("@Code", DbType.String, ParameterDirection.Input, Currency.Code));
                spInsert.AddParameter(new DBParameter("@Name", DbType.String, ParameterDirection.Input, Currency.Name));

                DBStoredProcedure spUpdate = new DBStoredProcedure();
                spUpdate.ProcedureName = "catUpdateCurrency";
                spUpdate.AddParameter(new DBParameter("@Id", DbType.Int32, ParameterDirection.Input, Currency.Id));
                spUpdate.AddParameter(new DBParameter("@Code", DbType.String, ParameterDirection.Input, Currency.Code));
                spUpdate.AddParameter(new DBParameter("@Name", DbType.String, ParameterDirection.Input, Currency.Name));

                DBStoredProcedure spDelete = new DBStoredProcedure();
                spDelete.ProcedureName = "catDeleteCurrency";
                spDelete.AddParameter(new DBParameter("@Id", DbType.Int32, ParameterDirection.Input, Currency.Id));

                this.AddStoredProcedure("InsertObject", spInsert);
                this.AddStoredProcedure("UpdateObject", spUpdate);
                this.AddStoredProcedure("DeleteObject", spDelete);

                DBStoredProcedure spSelect = new DBStoredProcedure();
                spSelect.ProcedureName = "catSelectCurrency";
                spSelect.AddParameter(new DBParameter("@Id", DbType.Int32, ParameterDirection.Input, Currency.Id));
                this.AddStoredProcedure("SelectObject", spSelect);
            }
        }
Exemplo n.º 24
0
 public void Show(ICurrency currency)
 {
     if ((mode & Target.Customer) == Target.Customer || showCashierMessage)
     {
         customerForm.Show(currency);
     }
 }
Exemplo n.º 25
0
        private async void OnPriceChanged()
        {
            Price price = Price;

            if (price == null)
            {
                Content = null;
                return;
            }

            if (price.Currency != currency?.UniqueCode)
            {
                currency = currencyProvider.Get(price.Currency);
                string symbol = await queryDispatcher.QueryAsync(new GetCurrencySymbol(price.Currency));

                if (symbol != currency.Symbol)
                {
                    currency = currency.ForCustomSymbol(symbol);
                }
            }

            Content = new TextBlock()
            {
                Text       = currency.Format(price.Value),
                FontSize   = FontSize,
                Foreground = Foreground,
            };
        }
Exemplo n.º 26
0
        public async Task <IActionResult> CurrencyEdit(Guid?currencyGuid)
        {
            ViewBag.Title   = "Edit Currency";
            ViewBag.Heading = "Edit Currency";

            CurrencyViewModel model = new CurrencyViewModel();

            if (currencyGuid.HasValue)
            {
                ICurrency currency = await dataManager.FetchCurrency(currencyGuid.Value);

                model.Guid  = currency.Guid;
                model.Title = currency.Title;
                model.Code  = currency.Code;

                //var node = SiteMaps.Current.FindSiteMapNodeFromKey("CurrencyEdit");
                //if (node != null)
                //{
                //    node.Title = "Edit Currency";
                //}
            }


            return(View(model));
        }
Exemplo n.º 27
0
 public void Setup()
 {
     _gold    = new Currency(Guid.NewGuid(), "Gold", "GLD", 0, 999);
     _itemDef = new ItemDefinition(Guid.NewGuid())
     {
         name        = "Root item",
         description = "Some description of root item",
         layoutShape = new ComplexShape2D(new bool[3, 3]
         {
             { true, false, false },
             { false, true, false },
             { false, false, true },
         }),
         maxStackSize = 3,
         buyPrice     = new CurrencyDecorator <double>[]
         {
             new CurrencyDecorator(_gold, 10d),
         },
         sellPrice = new CurrencyDecorator <double>[]
         {
             new CurrencyDecorator(_gold, 7d),
         }
     };
     _childItemDef = new ItemDefinition(Guid.NewGuid(), _itemDef)
     {
         name         = "Child item",
         description  = "Child description",
         maxStackSize = 10,
     };
 }
Exemplo n.º 28
0
 public ShopItem(int id, ICurrency price, ISellableItem item, List <ShopItemOption> shopItemOptions)
 {
     Id              = id;
     Price           = price;
     Item            = item;
     ShopItemOptions = shopItemOptions;
 }
Exemplo n.º 29
0
        public IActionResult Get(string moeda, int valorEmCentavos)
        {
            //Validar as entradas
            if (valorEmCentavos < 0)
            {
                return(BadRequest("Valor em centavos inválido"));
            }

            if (moeda == null || moeda.Length != 3)
            {
                return(BadRequest("Moeda inválida"));
            }

            ICurrency currency = FactoryCurrency.Create(moeda);

            IAPIExternalController apilayer = _APIExternalController;
            var taxas = apilayer.Live(currency.GetMoedas().ToArray());

            if (taxas == null)
            {
                return(StatusCode((int)HttpStatusCode.InternalServerError, "Erro interno, verificar logs ou solicitar ajuda ao administrador do sistema"));
            }
            if (!currency.IsValid(taxas))
            {
                return(BadRequest("Moeda desconhecida"));
            }

            double taxaUSD   = currency.GetTaxaUSD(taxas);
            double taxaMoeda = currency.GetTaxaMoeda(taxas);

            return(base.Ok(CalcularRetorno(valorEmCentavos, taxaUSD, taxaMoeda)));
        }
Exemplo n.º 30
0
 public CurrencyExchangeResult(ICurrency exchangedCurrency, double exchangedAmount, DateTime timestamp, object state)
 {
     ExchangedCurrency = exchangedCurrency;
     ExchangedAmount = exchangedAmount;
     Timestamp = timestamp;
     State = state;
 }
Exemplo n.º 31
0
        public virtual string Display(ICurrency currency)
        {
            // METHOD 1 - with foreach loop (did not remove code so reviewers could evaluate both methods)
            //StringBuilder sr = new StringBuilder();
            //foreach (Money money in currency.AllDenominations)
            //{
            //    if (money.Count > 0)
            //    {
            //        sr.Append(String.Format("{0} {1},", money.Count, money.Name));
            //    }
            //}

            // METHOD 2 - Using LINQ.. both one line and 2 line versions. 1 line version commented out due to complexity and clarity
            var money = currency.AllDenominations.Where(x => x.Count > 0);
            var sr    = money.Aggregate(new StringBuilder(), (x, y) => x.Append(String.Format("{0} {1},", y.Count, y.Name)));

            //var sr = currency.AllDenominations.Where(x => x.Count > 0).Aggregate(new StringBuilder(), (x, y) => x.Append(String.Format("{0} {1},", y.Count, y.Name)));

            if (sr.Length == 0)
            {
                return(String.Format("{0}\n", "No Change Due"));  // not part of the requirements, yet exact change is a viable value.
            }
            else
            {
                return(String.Format("{0}\n", sr.ToString().Trim(',')));
            }
        }
Exemplo n.º 32
0
        public void GetAllConversionsRecursive(ICurrency start, double startConversionRate, Dictionary <ICurrency, ConversionTable <ICurrency, double> .Row> dict)
        {
            foreach (var kvp in start.conversionTable.conversions)
            {
                var rate = kvp.Value.conversionRate * startConversionRate;

                // Already have this conversion in our table, and it's not better than we one we have.
                if (dict.ContainsKey(kvp.Key))
                {
                    if (rate > dict[kvp.Key].conversionRate)
                    {
                        // Conversion rate is better than we currently have.
                        dict[kvp.Key] = new ConversionTable <ICurrency, double> .Row(rate);

                        GetAllConversionsRecursive(kvp.Key, kvp.Value.conversionRate * startConversionRate, dict);
                    }

                    continue;
                }

                dict[kvp.Key] = new ConversionTable <ICurrency, double> .Row(rate);

                GetAllConversionsRecursive(kvp.Key, kvp.Value.conversionRate * startConversionRate, dict);
            }
        }
Exemplo n.º 33
0
        public async Task <bool> Add(
            ICurrency currency,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (currency == null)
            {
                return(false);
            }
            cancellationToken.ThrowIfCancellationRequested();

            if (currency.Guid == Guid.Empty)
            {
                currency.Guid = Guid.NewGuid();
            }

            bool result = await dbCurrency.Create(
                currency.Guid,
                currency.Title,
                currency.Code,
                currency.SymbolLeft,
                currency.SymbolRight,
                currency.DecimalPointChar,
                currency.ThousandsPointChar,
                currency.DecimalPlaces,
                currency.Value,
                currency.LastModified,
                currency.Created,
                cancellationToken);

            return(result);
        }
Exemplo n.º 34
0
 public void Show(ICurrency currency)
 {
     if ((mode & Target.Cashier) == Target.Cashier)
     {
         touchForm.Show(currency);
     }
 }
Exemplo n.º 35
0
        public async Task Update(
            ICurrency currency,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            ThrowIfDisposed();
            cancellationToken.ThrowIfCancellationRequested();
            if (currency == null)
            {
                throw new ArgumentException("currency must not be null");
            }
            if (currency.Id == Guid.Empty)
            {
                throw new ArgumentException("currency must have a non-empty id");
            }

            var c = Currency.FromICurrency(currency);

            bool tracking = dbContext.ChangeTracker.Entries <Currency>().Any(x => x.Entity.Id == c.Id);

            if (!tracking)
            {
                dbContext.Currencies.Update(c);
            }

            int rowsAffected = await dbContext.SaveChangesAsync(cancellationToken)
                               .ConfigureAwait(false);
        }
Exemplo n.º 36
0
        static void Main()
        {
            Console.WriteLine("Select currency: £ = 1, $ = 2");

            ICurrency currency = CurrencySelector.CurrencySelect(Console.ReadLine());

            if (currency != null)
            {
                Console.WriteLine("What is the till's float?");

                if (int.TryParse(Console.ReadLine(), out int cashFloat))
                {
                    currency = CurrencyCalc.SetFloat(cashFloat, currency);
                }

                foreach (int denomination in currency.Denominations)
                {
                    Console.WriteLine(currency.SpecifiedCurrency + denomination);

                    if (int.TryParse(Console.ReadLine(), out int numberOfdenominations))
                    {
                        currency = CurrencyCalc.CalculateCurrency(numberOfdenominations, denomination, currency);
                    }
                }

                currency = CurrencyCalc.CalculateBankingTotal(currency);

                Console.WriteLine("Total cash in the till: " + currency.SpecifiedCurrency + currency.CashTotal);
                Console.WriteLine("Total Amount of cash to be banked: " + currency.SpecifiedCurrency + currency.BankingTotal);
            }
            else
            {
                Console.WriteLine("No Valid currency selected");
            }
        }
Exemplo n.º 37
0
        /// <summary>
        /// The formatted price.
        /// </summary>
        /// <param name="display">
        /// The display.
        /// </param>
        /// <param name="currency">
        /// The currency.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        public static string FormattedPrice(this ProductDisplay display, ICurrency currency)
        {
            if (!display.ProductVariants.Any())
            {
                return(FormatPrice(display.Price, currency));
            }

            var variants   = display.ProductVariants.ToArray();
            var onsaleLow  = variants.Any(x => x.OnSale) ? variants.Where(x => x.OnSale).Min(x => x.SalePrice) : 0;
            var low        = variants.Any(x => !x.OnSale) ? variants.Where(x => !x.OnSale).Min(x => x.Price) : 0;
            var onSaleHigh = variants.Any(x => x.OnSale) ? variants.Where(x => x.OnSale).Max(x => x.SalePrice) : 0;
            var max        = variants.Any(x => !x.OnSale) ? variants.Where(x => !x.OnSale).Max(x => x.Price) : 0;

            if (variants.Any(x => x.OnSale))
            {
                low = onsaleLow < low ? onsaleLow : low;
                max = max > onSaleHigh ? max : onSaleHigh;
            }

            if (low != max)
            {
                return(string.Format(
                           "{0} - {1}",
                           FormatPrice(low, currency),
                           FormatPrice(max, currency)));
            }

            return(FormatPrice(display.Price, currency));
        }
Exemplo n.º 38
0
 public ShopItem(int id, ICurrency price, ISellableItem item)
 {
     Id              = id;
     Price           = price;
     Item            = item;
     ShopItemOptions = new List <ShopItemOption>();
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="CheckoutManagerSummaryFactory"/> class.
        /// </summary>
        /// <param name="currency">
        /// The <see cref="ICurrency"/>.
        /// </param>
        /// <param name="basketLineItemFactory">
        /// The basket Line Item Factory.
        /// </param>
        public CheckoutManagerSummaryFactory(ICurrency currency, BasketLineItemFactory basketLineItemFactory)
        {
            Mandate.ParameterNotNull(currency, "currency");
            Mandate.ParameterNotNull(basketLineItemFactory, "basketLineItemFactory");

            _currency = currency;
            _basketLineItemFactory = basketLineItemFactory;
        }
Exemplo n.º 40
0
Arquivo: Iso4217.cs Projeto: haf/Money
 /// <summary>
 /// Return currency from number code
 /// </summary>
 /// <param name="numCode">
 /// number code
 /// </param>
 /// <param name="currency">
 /// currency
 /// </param>
 /// <returns>
 /// true if ISO 4217 contain this currency
 /// </returns>
 public static bool TryParse(int numCode, out ICurrency currency)
 {
     currency = Parse(numCode);
     if(currency != null)
         return true;
     currency = new UnknownCurrency(numCode);
     return false;
 }
Exemplo n.º 41
0
Arquivo: Iso4217.cs Projeto: haf/Money
 /// <summary>
 /// Return currency from character code
 /// </summary>
 /// <param name="charCode">
 /// character code
 /// </param>
 /// <param name="currency">
 /// currency
 /// </param>
 /// <returns>
 /// true if ISO 4217 contain this currency
 /// </returns>
 public static bool TryParse(string charCode, out ICurrency currency)
 {
     currency = Parse(charCode);
     if(currency != null)
         return true;
     currency = new UnknownCurrency(charCode);
     return false;
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="SalePreparationSummaryFactory"/> class.
        /// </summary>
        /// <param name="currency">
        /// The <see cref="ICurrency"/>.
        /// </param>
        /// <param name="basketLineItemFactory">
        /// The basket Line Item Factory.
        /// </param>
        public SalePreparationSummaryFactory(ICurrency currency, BasketLineItemFactory basketLineItemFactory)
        {
            Mandate.ParameterNotNull(currency, "currency");
            Mandate.ParameterNotNull(basketLineItemFactory, "basketLineItemFactory");

            _currency = currency;
            _basketLineItemFactory = basketLineItemFactory;
        }
Exemplo n.º 43
0
        public AccountDetailsView(ICurrency baseCurrency)
        {
            Money zeroAmount = new Money(0m, baseCurrency);
            TotalAll = zeroAmount.DisplayString;
            TotalPositions = TotalAll;
            TotalCash = TotalAll;

            Status = AccountStati.Active;
            StatusIsOpen = true;
        }
Exemplo n.º 44
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BasketLineItemFactory"/> class.
        /// </summary>
        /// <param name="umbraco">
        /// The umbraco.
        /// </param>
        /// <param name="currentCustomer">
        /// The current Customer.
        /// </param>
        /// <param name="currency">
        /// The currency.
        /// </param>
        public BasketLineItemFactory(UmbracoHelper umbraco, ICustomerBase currentCustomer, ICurrency currency)
        {
            Mandate.ParameterNotNull(umbraco, "umbraco");
            Mandate.ParameterNotNull(currency, "currency");
            Mandate.ParameterNotNull(currentCustomer, "currentCustomer");

            this._umbraco = umbraco;
            this._currency = currency;
            this._currentCustomer = currentCustomer;
        }
Exemplo n.º 45
0
        public CommCalc(string name, ICurrency commCurrency, Money minValue, Money maxValue,
			Money fixedSetup)
        {
            Name = name;
            CommCurrency = commCurrency;
            MinValue = minValue;
            MaxValue = maxValue;
            FixedSetup = fixedSetup;

            checkCurrencies();
        }
Exemplo n.º 46
0
 private bool isCurrencyLoaded(string Symbol, ref ICurrency LoadedCurrency)
 {
     foreach (ICurrency c in theCurrencies)
     {
         if (c.Symbol == Symbol)
         {
             LoadedCurrency = c;
             return true;
         }
     }
     return false;
 }
Exemplo n.º 47
0
 /// <summary>
 /// Builds a <see cref="AddItemModel"/> from <see cref="IProductContent"/>.
 /// </summary>
 /// <param name="product">
 /// The product.
 /// </param>
 /// <param name="currency">
 /// The currency.
 /// </param>
 /// <param name="showWishList">
 /// The show wish list.
 /// </param>
 /// <returns>
 /// The <see cref="AddItemModel"/>.
 /// </returns>
 public static AddItemModel BuildAddItemModel(this IProductContent product, ICurrency currency, bool showWishList)
 {
     return new AddItemModel()
         {
             Product = product.AsProductDisplay(),
             ContentId = 0,
             BasketPageId = BazaarContentHelper.GetBasketContent().Id,
             ShowWishList = showWishList,
             WishListPageId = BazaarContentHelper.GetWishListContent().Id,
             Currency = currency
         };
 }
Exemplo n.º 48
0
 public InstructionEngineParameters(PricingTypes pricingType, decimal minimumQty, ICurrency underlying)
 {
     this.pricingType = pricingType;
     switch (pricingType)
     {
         case PricingTypes.Direct:
             this.minimumRebalanceAmount = new Money(minimumQty, underlying);
             break;
         case PricingTypes.Percentage:
             this.minimumRebalancePercentage = minimumQty;
             break;
     }
 }
Exemplo n.º 49
0
        public FeeCalc(FeeType feeType, string name, ICurrency feeCurrency, IAssetManager assetManager)
            : this()
        {
            if ((feeType == null || feeType.Key == FeeTypes.None)|| string.IsNullOrEmpty(name) || feeCurrency == null || assetManager == null)
                throw new ApplicationException("Not all parameters are passed in to instantiate a new fee calculation");

            FeeType = feeType;
            Name = name;
            FeeCurrency = feeCurrency;
            this.AssetManager = assetManager;

            checkData();
        }
Exemplo n.º 50
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="parent">Parent order</param>
 /// <param name="feeFactory">Fee factory to use for calculating transaction costs</param>
 internal MonetaryOrder(IOrderAmountBased parent, IFeeFactory feeFactory)
     : base(parent.Account, (parent.Amount - parent.Commission))
 {
     if (parent.TradedInstrument != null && parent.TradedInstrument.IsTradeable)
     {
         ITradeableInstrument instrument = (ITradeableInstrument)parent.TradedInstrument;
         this.requestedCurrency = instrument.CurrencyNominal;
         checkInitialValues();
         setCommission(feeFactory);
         this.moneyParent = parent;
     }
     else
         throw new ApplicationException("Can not insert a monetary order without a requested currency");
 }
Exemplo n.º 51
0
        /// <summary>
        /// Gets historical exchange rate by currency and time
        /// </summary>
        /// <param name="session">Data access object</param>
        /// <param name="currency">Currency</param>
        /// <param name="date">Date</param>
        /// <returns>Historical exchange object</returns>
        public static IHistoricalExRate GetHistoricalExRate(IDalSession session, ICurrency currency, DateTime date)
        {
            IList list;
            IHistoricalExRate rate = null;

            List<ICriterion> expressions = new List<ICriterion>();
            expressions.Add(Expression.Eq("Currency.Key", currency.Key));
            expressions.Add(Expression.Eq("RateDate", date));
            list = session.GetList(typeof(HistoricalExRate), expressions);
            if (list != null && list.Count > 0)
            {
                rate = (IHistoricalExRate)list[0];
            }
            return rate;
        }
Exemplo n.º 52
0
        /// <summary>
        /// Constructor of CommValueDetails object
        /// </summary>
        /// <param name="detailsToCopy">The object we want to clone from</param>
        /// <param name="commCurrency">The new currency to convert to</param>
        /// <param name="detailsToCopy">The ex rate to use</param>
        internal CommValueDetails(ICommValueDetails detailsToCopy, ICurrency commCurrency, decimal exRate)
        {
            Money commission;
            if (detailsToCopy == null || detailsToCopy.CommLines.Count == 0)
                throw new ApplicationException("It is not possible to clone the commissiondetails when they are null");

            foreach (ICommValueBreakupLine line in detailsToCopy.CommLines)
            {
                if (line.CommCurrency.Equals(commCurrency))
                    commission = line.CalcValue;
                else
                    commission = line.CalcValue.Convert(exRate, commCurrency);

                AddLine(line.CalcType, commission, line.CalcInfo);
            }
        }
Exemplo n.º 53
0
        public static Currency FromICurrency(ICurrency icurrency)
        {
            Currency c = new Currency();
            c.Guid = icurrency.Guid;
            c.Title = icurrency.Title;
            c.Code = icurrency.Code;

            c.SymbolLeft = icurrency.SymbolLeft;
            c.SymbolRight = icurrency.SymbolRight;
            c.DecimalPointChar = icurrency.DecimalPointChar;
            c.ThousandsPointChar = icurrency.ThousandsPointChar;
            c.DecimalPlaces = icurrency.DecimalPlaces;
            c.Value = icurrency.Value;

            return c;
        }
Exemplo n.º 54
0
 internal AggregatedCashValuation(ValuationCollection cashValuations, bool aggregateToBase)
 {
     bool hasInitialized = false;
     if (aggregateToBase)
     {
         foreach (IValuation valuation in cashValuations)
         {
             if (valuation.Instrument.IsCash)
             {
                 if (this.account == null)
                 {
                     this.account = valuation.Account;
                     this.date = valuation.Date;
                     this.key = valuation.Key;
                     this.marketRate = 1M;
                     this.avgOpenExRate = 1M;
                     baseCurrency = ((ICurrency)valuation.Instrument).BaseCurrency;
                     price = new Price(1M, baseCurrency, baseCurrency);
                     this.bookPrice = price;
                     this.costPrice = price;
                     this.marketPrice = price;
                     this.displayInstrumentsCategory = valuation.DisplayInstrumentsCategory;
                     this.AssetClass = valuation.ValuationMutation.AssetClass;
                     this.ValuationMutation = valuation.ValuationMutation;
                 }
                 this.size += valuation.BaseMarketValue;
                 this.bookValue += valuation.BookValue;
                 this.bookChange += valuation.BookChange;
                 this.deposit += valuation.Deposit;
                 this.withDrawal += valuation.WithDrawal;
                 if (!valuation.ValuationMutation.IsSecurityValuationMutation)
                 {
                     this.depositToDate += ((IMonetaryValuationMutation)valuation.ValuationMutation).DepositToDate;
                     this.withDrawalToDate += ((IMonetaryValuationMutation)valuation.ValuationMutation).WithDrawalToDate;
                 }
                 hasInitialized = true;
             }
         }
     }
     if (!hasInitialized)
         throw new ApplicationException("Class AggregatedCashValuation could not be initialized");
 }
Exemplo n.º 55
0
        public IGLLookupRecord GetGLLookupRecord(
                ICurrency currency,
                bool isExternalExecution,
                bool isInternalExecution,
                bool isUnsettled,
                BookingComponentTypes bookingComponentType)
        {
            var returnvalue = from c in Records
                              where ((c.IsExternalExecution == isExternalExecution)
                                && (c.IsInternalExecution == isInternalExecution)
                                && (c.IsUnSettled == isUnsettled)
                                && (c.BookingComponentType == bookingComponentType)
                                && (c.Currency.Equals(currency)))
                              select c;

            if (returnvalue.Count() == 0)
                throw new ApplicationException("No Lookup record is matched.");

            return returnvalue.ElementAt(0);
        }
Exemplo n.º 56
0
        protected static Tuple<double[,], double[]> computeCorrelationAndVol(DateTime priceDate, IAsset underlying, ICurrency cur, int date_nb)
        {
            List<DateTime> dates_correl = new List<DateTime>();
            int total = 0, real = 0; // current number of date : total also have not taken dates cause week end
            while (real < date_nb)
            {
                DateTime curr_date = priceDate - TimeSpan.FromDays(total);
                if (!(curr_date.DayOfWeek == DayOfWeek.Saturday || curr_date.DayOfWeek == DayOfWeek.Sunday))
                {
                    dates_correl.Add(curr_date);
                    real++;
                }
                total++;
            }
            // get the prices from database
            Dictionary<DateTime, double> hist_correl = AccessDB.Get_Asset_Price(underlying.getName(), dates_correl);
            // transform the Tuple format to double[,] format
            double[,] hist_correl_double = new double[2, date_nb];
            int j = 0;
            foreach (DateTime d in dates_correl)
            {
                hist_correl_double[0, j] = hist_correl[d];
                j++;
            }
            j = 0;
            foreach (DateTime d in dates_correl)
            {
                hist_correl_double[1, j] = 1 / cur.getChangeToEuro(d);
                j++;
            }

            // compute correl and vol using C++ functions
            Wrapping.Tools tools = new Wrapping.Tools();
            double[,] correl = new double[2, 2];
            double[] vol = new double[2];
            tools.getCorrelAndVol(date_nb, 2, hist_correl_double, correl, vol);
            return new Tuple<double[,], double[]>(correl, vol);
        }
Exemplo n.º 57
0
        public static IGLAccount GetSettlementDifferenceGLAccount(IDalSession session, ICurrency currency, ITradeableInstrument instrument)
        {
            IGLAccount glAccount = null;
            if (instrument.SettlementDifferenceAccount != null)
                glAccount = instrument.SettlementDifferenceAccount;
            else
            {
                List<ICriterion> expressions = new List<ICriterion>();
                expressions.Add(Expression.Eq("IsSettlementDifference", true));
                IList<IGLAccount> list = session.GetTypedList<GLAccount, IGLAccount>(expressions);
                if (list != null)
                {
                    if (list.Count == 1)
                        glAccount = list[0];
                    else if (list.Count > 1)
                        glAccount = list.Where(x => x.DefaultCurrency.Equals(currency)).FirstOrDefault();
                }
            }

            if (glAccount == null)
                throw new ApplicationException("Lookup of Settlement Difference GL Account produced no account.");
            else
                return glAccount;
        }
Exemplo n.º 58
0
 private void LoadFromReader(DbDataReader reader, ICurrency currency)
 {
     currency.Guid = new Guid(reader["Guid"].ToString());
     currency.Title = reader["Title"].ToString();
     currency.Code = reader["Code"].ToString();
     currency.SymbolLeft = reader["SymbolLeft"].ToString();
     currency.SymbolRight = reader["SymbolRight"].ToString();
     currency.DecimalPointChar = reader["DecimalPointChar"].ToString();
     currency.ThousandsPointChar = reader["ThousandsPointChar"].ToString();
     currency.DecimalPlaces = reader["DecimalPlaces"].ToString();
     currency.Value = Convert.ToDecimal(reader["Value"]);
     currency.LastModified = Convert.ToDateTime(reader["LastModified"]);
     currency.Created = Convert.ToDateTime(reader["Created"]);
 }
Exemplo n.º 59
0
        public async Task<bool> Save(ICurrency currency)
        {
            if (currency == null) { return false; }
            bool result;
            if (currency.Guid == Guid.Empty)
            {
                currency.Guid = Guid.NewGuid();

                result = await dbCurrency.Create(
                    currency.Guid,
                    currency.Title,
                    currency.Code,
                    currency.SymbolLeft,
                    currency.SymbolRight,
                    currency.DecimalPointChar,
                    currency.ThousandsPointChar,
                    currency.DecimalPlaces,
                    currency.Value,
                    currency.LastModified,
                    currency.Created);
            }
            else
            {
                result = await dbCurrency.Update(
                    currency.Guid,
                    currency.Title,
                    currency.Code,
                    currency.SymbolLeft,
                    currency.SymbolRight,
                    currency.DecimalPointChar,
                    currency.ThousandsPointChar,
                    currency.DecimalPlaces,
                    currency.Value,
                    currency.LastModified);

            }

            return result;
        }
Exemplo n.º 60
0
 public Quarter()
 {
     volume = new FluidOunces();
     volume.Unit = 270;
     currency = new USCurrency();
     currency.UnitPrice = 25;
 }