コード例 #1
0
        /// <summary>
        /// 货币转换
        /// </summary>
        /// <param name="forme"></param>
        /// <param name="toCode"></param>
        /// <param name="rate"></param>
        /// <returns></returns>
        public static Money TryTo(this Money forme, CurrencyIsoCode toCode, Func <Func <IExchangeRateProvider> > rate, Money defVal = default(Money))
        {
            ExchangeRateProvider.Factory = rate();
            var cVal = forme.TryConvert().To(toCode);

            return(cVal.HasValue ? cVal.Value : defVal);
        }
コード例 #2
0
            /// <summary>
            /// Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent <see cref="CurrencyIsoCode"/>.
            /// </summary>
            /// <remarks>The <paramref name="isoCode"/> can represent an alphabetic or a numeric currency code.
            /// <para>In the case of alphabetic codes, parsing is case-insensitive.</para>
            /// <para>Only defined numeric codes can be parsed.</para></remarks>
            /// <para>If the convertion fails, <paramref name="defaultValue"/> will be returned.</para>
            /// <param name="isoCode">A string containing the name or value to convert.</param>
            /// <param name="defaultValue">The value to return if the convertion fails.</param>
            /// <returns>An object of type <see cref="CurrencyIsoCode"/> whose value is represented by value.</returns>
            /// <exception cref="ArgumentNullException"><paramref name="isoCode"/> is null.</exception>
            /// <exception cref="System.ComponentModel.InvalidEnumArgumentException"><paramref name="isoCode"/> does not represent a defined alphabetic or numeric code.</exception>
            /// <seealso cref="IsoCodeExtensions.AlphabeticCode"/>
            /// <seealso cref="IsoCodeExtensions.NumericCode"/>
            public static CurrencyIsoCode Parse(string isoCode, CurrencyIsoCode defaultValue)
            {
                CurrencyIsoCode?parsed;

                TryParse(isoCode, out parsed);
                return(parsed.GetValueOrDefault(defaultValue));
            }
コード例 #3
0
 public static Currency Get(CurrencyIsoCode isOCode)
 {
     return(new Currency()
     {
         currencyCode = isOCode
     });
 }
コード例 #4
0
ファイル: Currency.cs プロジェクト: shadowca/nmoneys
        /// <summary>
        /// Allows setting all field both for constructors and serialization methods.
        /// </summary>
        private void setAllFields(CurrencyIsoCode isoCode, string englishName, string nativeName, string symbol, int significantDecimalDigits, string decimalSeparator, string groupSeparator, int[] groupSizes, int positivePattern, int negativePattern, bool isObsolete, CharacterReference entity)
        {
            IsoCode                  = isoCode;
            EnglishName              = englishName;
            Symbol                   = symbol;
            AlphabeticCode           = IsoSymbol = isoCode.ToString();
            SignificantDecimalDigits = significantDecimalDigits;
            NativeName               = nativeName;
            DecimalSeparator         = decimalSeparator;
            GroupSeparator           = groupSeparator;
            GroupSizes               = groupSizes;
            PositivePattern          = positivePattern;
            NegativePattern          = negativePattern;
            IsObsolete               = isObsolete;
            Entity                   = entity;

            FormatInfo = NumberFormatInfo.ReadOnly(new NumberFormatInfo
            {
                CurrencySymbol           = symbol,
                CurrencyDecimalDigits    = significantDecimalDigits,
                CurrencyDecimalSeparator = decimalSeparator,
                CurrencyGroupSeparator   = groupSeparator,
                CurrencyGroupSizes       = groupSizes,
                CurrencyPositivePattern  = positivePattern,
                CurrencyNegativePattern  = negativePattern,
                NumberDecimalDigits      = significantDecimalDigits,
                NumberDecimalSeparator   = decimalSeparator,
                NumberGroupSeparator     = groupSeparator,
                NumberGroupSizes         = groupSizes,
                NumberNegativePattern    = negativePattern.TranslateNegativePattern(),
            });
        }
コード例 #5
0
        public ActionResult Detail(CurrencyIsoCode code)
        {
            Currency currency = Currency.Get(code);
            var      snapshot = new Snapshot(currency);

            return(PartialView(snapshot));
        }
コード例 #6
0
 public void currency_codes_are_modeled_as_enums_named_after_its_ISO_alphabetic_code()
 {
     CurrencyIsoCode usDollars   = CurrencyIsoCode.USD;
     CurrencyIsoCode euro        = CurrencyIsoCode.EUR;
     CurrencyIsoCode danishKrona = CurrencyIsoCode.DKK;
     CurrencyIsoCode noCurrency  = CurrencyIsoCode.XXX;
 }
コード例 #7
0
ファイル: ProvidersTesters.cs プロジェクト: shadowca/nmoneys
        public void Get_UndefinedCurrency_Exception()
        {
            CurrencyIsoCode notDefined = (CurrencyIsoCode)(-1);

            Assert.That(() => new EmbeddedXmlProvider().Get(notDefined),
                        Throws.InstanceOf <MisconfiguredCurrencyException>().With.Message.Contains("-1"));
        }
コード例 #8
0
 /// <summary>
 /// Asserts whether a currency is compatible with this exchange rate, that is, is the same as <see cref="From"/>.
 /// </summary>
 /// <param name="from">The currency to check its compatibility againsts the base currency.</param>
 /// <exception cref="DifferentCurrencyException"><paramref name="from"/> is not compatible.</exception>
 private void assertCompatibility(CurrencyIsoCode from)
 {
     if (from != From)
     {
         throw new DifferentCurrencyException(From.AlphabeticCode(), from.AlphabeticCode());
     }
 }
コード例 #9
0
ファイル: CurrencyDemo.cs プロジェクト: shadowca/nmoneys
        public void whenever_a_deprecated_currency_is_obtained_an_event_is_raised()
        {
            bool            called   = false;
            CurrencyIsoCode obsolete = CurrencyIsoCode.XXX;
            EventHandler <ObsoleteCurrencyEventArgs> callback = (sender, e) =>
            {
                called   = true;
                obsolete = e.Code;
            };

            try
            {
                Currency.ObsoleteCurrency += callback;
                Currency.Get("EEK");

                Assert.That(called, Is.True);
                Assert.That(obsolete.ToString(), Is.EqualTo("EEK"));
                Assert.That(obsolete.AsAttributeProvider(), Has.Attribute <ObsoleteAttribute>());
            }
            // DO unsubscribe from global events whenever listening isnot needed anymore
            finally
            {
                Currency.ObsoleteCurrency -= callback;
            }
        }
コード例 #10
0
        internal static CurrencyInfo ReadInfo(XPathNavigator navigator, CurrencyIsoCode code)
        {
            XPathNavigator node = navigator.SelectSingleNode(string.Format(CultureInfo.InvariantCulture, "/currencies/currency[@code='{0}']", code));

            if (node == null)
            {
                throw new MisconfiguredCurrencyException(code);
            }

            CurrencyInfo info = new CurrencyInfo(
                code,
                node.SelectMandatory(englishName),
                node.SelectMandatory(nativeName),
                node.SelectMandatory(symbol),
                node.SelectMandatory(significantDecimalDigits, n => n.ValueAsInt),
                node.SelectMandatory(decimalSeparator),
                node.SelectMandatory(groupSeparator),
                node.SelectMandatory(groupSizes),
                node.SelectMandatory(positivePattern, n => n.ValueAsInt),
                node.SelectMandatory(negativePattern, n => n.ValueAsInt),
                node.SelectOptional(obsolete, n => n.ValueAsBoolean),
                node.SelectOptional(entity,
                                    n => CurrencyCharacterReferences.Get(n.Value),
                                    CharacterReference.Empty));

            return(info);
        }
コード例 #11
0
 private static void populateDictionary(Dictionary <CurrencyIsoCode, int> map, CurrencyIsoCode[] values, int iters)
 {
     for (var i = 0; i < iters; i++)
     {
         CurrencyIsoCode code = values[i % values.Length];
         map[code] = i;
     }
 }
コード例 #12
0
ファイル: Currency.cs プロジェクト: shadowca/nmoneys
 internal static void RaiseIfObsolete(CurrencyIsoCode code)
 {
     if (ObsoleteCurrencies.IsObsolete(code))
     {
         EventHandler <ObsoleteCurrencyEventArgs> handler = ObsoleteCurrency;
         handler?.Invoke(null, new ObsoleteCurrencyEventArgs(code));
     }
 }
コード例 #13
0
        public void Get_ToEUR_CorrectRate(CurrencyIsoCode from, decimal rate)
        {
            ExchangeRate toEuro = _as20110519.Get(from, CurrencyIsoCode.EUR);

            Assert.That(toEuro.From, Is.EqualTo(from));
            Assert.That(toEuro.To, Is.EqualTo(CurrencyIsoCode.EUR));
            Assert.That(toEuro.Rate, Is.EqualTo(rate));
        }
コード例 #14
0
        public void Print(CurrencyIsoCode currency, FileInfo file)
        {
            IsoCurrency fromIso = loadIsoCurrency(file, currency);

            pushDiff(fromIso, Currency.Get(fromIso.AlphabeticalCode));

            MaybeWrite("discrepancies with iso.org");
        }
コード例 #15
0
 public void Shortcuts_MinimalInfoConfigured(Currency shortcut, CurrencyIsoCode isoCode, string isoSymbol, string symbol, string englishName)
 {
     Assert.That(shortcut.IsoCode, Is.EqualTo(isoCode));
     Assert.That(shortcut.IsoSymbol, Is.EqualTo(isoSymbol));
     Assert.That(shortcut.AlphabeticCode, Is.EqualTo(isoSymbol));
     Assert.That(shortcut.Symbol, Is.EqualTo(symbol));
     Assert.That(shortcut.EnglishName, Is.EqualTo(englishName));
 }
コード例 #16
0
        public void Get_FromEUR_CorrectRate(CurrencyIsoCode to, decimal rate)
        {
            ExchangeRate fromEuro = _as20110519.Get(CurrencyIsoCode.EUR, to);

            Assert.That(fromEuro.From, Is.EqualTo(CurrencyIsoCode.EUR));
            Assert.That(fromEuro.To, Is.EqualTo(to));
            Assert.That(fromEuro.Rate, Is.EqualTo(rate), "no error margin is needed");
        }
コード例 #17
0
 private CanonicalCultureAttribute ensureCanonical(CurrencyIsoCode currency)
 {
     if (!Enumeration.TryGetAttribute(currency, out CanonicalCultureAttribute attribute))
     {
         writeError($"Currency '{currency}' not decorated with '{nameof(CanonicalCultureAttribute)}'.");
         Environment.Exit(-1);
     }
     return(attribute);
 }
コード例 #18
0
        public void Get_FromEUR_CorrectRate(CurrencyIsoCode to, decimal rate)
        {
            ExchangeRate fromEuro = _as20110519.Get(CurrencyIsoCode.EUR, to);

            Assert.That(fromEuro.From, Is.EqualTo(CurrencyIsoCode.EUR));
            Assert.That(fromEuro.To, Is.EqualTo(to));
            Assert.That(fromEuro.Rate, Is.EqualTo(rate)
                        .Within(0.00001m), "as it was built from USD, EUR direct rates have more decimals");
        }
コード例 #19
0
        public Money ReadFrom(BsonDeserializationContext context, BsonDeserializationArgs args)
        {
            context.Reader.ReadStartDocument();
            decimal         amount       = readAmount(context.Reader);
            CurrencyIsoCode currencyCode = readCurrency(context, args);

            context.Reader.ReadEndDocument();
            return(new Money(amount, currencyCode));
        }
コード例 #20
0
 public void BinaryDeserialization_OfObsoleteCurrency_DoesNotRaiseEvent(CurrencyIsoCode obsolete)
 {
     using (var serializer = new BinaryRoundtripSerializer <CurrencyIsoCode>())
     {
         serializer.Serialize(obsolete);
         Action deserializeObsolete = () => serializer.Deserialize();
         Assert.That(deserializeObsolete, Must.Not.Raise.ObsoleteEvent());
     }
 }
コード例 #21
0
        public void Get_ToEURInverse_CorrectRate(CurrencyIsoCode from, decimal rate)
        {
            ExchangeRate toEuro   = _as20110519.Get(from, CurrencyIsoCode.EUR);
            ExchangeRate inversed = toEuro.Invert();

            Assert.That(inversed.From, Is.EqualTo(CurrencyIsoCode.EUR));
            Assert.That(inversed.To, Is.EqualTo(from));
            Assert.That(inversed.Rate, Is.EqualTo(rate));
        }
コード例 #22
0
        public void Round_WithMode_Spec(CurrencyIsoCode currency, MidpointRounding mode, decimal amount, decimal roundedAmount)
        {
            var subject = new Money(amount, currency);

            Money rounded = subject.Round(mode);

            Assert.That(rounded, Is.Not.SameAs(subject));
            Assert.That(rounded.CurrencyCode, Is.EqualTo(currency));
            Assert.That(rounded.Amount, Is.EqualTo(roundedAmount));
        }
コード例 #23
0
        public void Get_FromEURInverse_CorrectRate(CurrencyIsoCode to, decimal rate)
        {
            ExchangeRate fromEuro = _as20110519.Get(CurrencyIsoCode.EUR, to);
            ExchangeRate inversed = fromEuro.Invert();

            Assert.That(inversed.From, Is.EqualTo(to));
            Assert.That(inversed.To, Is.EqualTo(CurrencyIsoCode.EUR));
            Assert.That(inversed.Rate, Is.EqualTo(rate)
                        .Within(0.00001m), "within 5 decimals error as Invert() uses decimal arithmetic");
        }
コード例 #24
0
        /// <summary>
        /// Initializes an instance of <see cref="ExchangeRate"/> with the provided information.
        /// </summary>
        /// <param name="from">Base currency, the currency from which the conversion is performed.</param>
        /// <param name="to">Quote currency, the currency which the conversion is performed to.</param>
        /// <param name="rate">A non-negative <see cref="decimal"/> instance representing the relative vaue of <paramref name="from"/> against <paramref name="to"/>.</param>
        /// <example>{from}= EUR, {to}= USD, {rate}=1.2500, represented as "EUR/USD 1.2500" means that one euro is exchanged for 1.2500 US dollars.</example>
        /// <exception cref="InvalidEnumArgumentException"><paramref name="from"/> or <paramref name="to"/> are undefined currencies.</exception>
        /// <exception cref="ArgumentException"><paramref name="rate"/> is negative.</exception>
        public ExchangeRate(CurrencyIsoCode from, CurrencyIsoCode to, decimal rate)
        {
            Guard.AgainstArgument("rate", rate < 0, "Non-negative");
            Enumeration.AssertDefined(from);
            Enumeration.AssertDefined(to);

            From = from;
            To   = to;
            Rate = rate;
        }
コード例 #25
0
ファイル: ProvidersTesters.cs プロジェクト: shadowca/nmoneys
        public void Get_UndefinedCurrency_Exception()
        {
            CurrencyIsoCode notDefined = (CurrencyIsoCode)(-1);

            using (var subject = new EmbeddedXmlInitializer())
            {
                Assert.That(() => subject.Get(notDefined),
                            Throws.InstanceOf <MisconfiguredCurrencyException>().With.Message.Contains("-1"));
            }
        }
コード例 #26
0
        public void Get_ToEURInverse_CorrectRate(CurrencyIsoCode from, decimal rate)
        {
            ExchangeRate toEuro   = _as20110519.Get(from, CurrencyIsoCode.EUR);
            ExchangeRate inversed = toEuro.Invert();

            Assert.That(inversed.From, Is.EqualTo(CurrencyIsoCode.EUR));
            Assert.That(inversed.To, Is.EqualTo(from));
            Assert.That(inversed.Rate, Is.EqualTo(rate)
                        .Within(0.00001m), "within 5 decimals due to precision of Invert()");
        }
コード例 #27
0
 public void BinaryDeserialization_DoesNotPreservesInstanceUniqueness()
 {
     using (var serializer = new BinaryRoundtripSerializer <CurrencyIsoCode>())
     {
         CurrencyIsoCode usd = CurrencyIsoCode.USD;
         serializer.Serialize(CurrencyIsoCode.USD);
         Assert.That(serializer.Deserialize(), Is.Not.SameAs(usd)
                     .And.EqualTo(usd));
     }
 }
コード例 #28
0
ファイル: CurrencyDemo.cs プロジェクト: shadowca/nmoneys
        public void Get_throws_if_currency_cannot_be_found()
        {
            CurrencyIsoCode notDefined = (CurrencyIsoCode)0;

            Assert.That(() => Currency.Get(notDefined), Throws.InstanceOf <ArgumentException>());
            Assert.That(() => Currency.Get("notAnIsoCode"), Throws.InstanceOf <ArgumentException>());
            CultureInfo neutralCulture = CultureInfo.GetCultureInfo("da");

            Assert.That(() => Currency.Get(neutralCulture), Throws.InstanceOf <ArgumentException>());
        }
コード例 #29
0
        /// <summary>
        /// Adds a rate, its inverse and identity rates for both base and quote currency for its later retrieval.
        /// </summary>
        /// <param name="from">Base currency, the currency from which the conversion is performed.</param>
        /// <param name="to">Quote currency, the currency which the conversion is performed to.</param>
        /// <param name="rate">A non-negative <see cref="decimal"/> instance representing the relative vaue of <paramref name="from"/> against <paramref name="to"/>.</param>
        /// <returns>The <see cref="ExchangeRatePair"/> just added as per the rules specified in the constructor.</returns>
        public ExchangeRatePair MultiAdd(CurrencyIsoCode from, CurrencyIsoCode to, decimal rate)
        {
            Add(to, to, 1m);
            Add(from, from, 1m);

            ExchangeRate direct  = Add(from, to, rate);
            ExchangeRate inverse = Add(to, from, direct.Invert().Rate);

            return(new ExchangeRatePair(direct, inverse));
        }
コード例 #30
0
ファイル: Quickstart.cs プロジェクト: briandwilson/nmoneys
        public void CurrencyCode_GetInstance()
        {
            CurrencyIsoCode usd = Currency.Code.Cast(840);
            CurrencyIsoCode eur = Currency.Code.Parse("eur");

            CurrencyIsoCode?maybeAud;

            Currency.Code.TryCast(36, out maybeAud);
            Currency.Code.TryParse("036", out maybeAud);
        }