public double Sell(Currencies currency, double amount) { try { if (!UseAsmx) { // Call the WCF service currencyProx = currencyChf.CreateChannel(); return currencyProx.Sell(currency, amount); } else { // Call the WCF service currencyAsmxProx = currencyAsmxChf.CreateChannel(); return currencyAsmxProx.Sell(currency, amount); } } catch (Exception ex) { LoggingManager.Logger.Log(LoggingCategory.Error, StringsResource.FailedToContactCurrencyExchange + " " + ex.Message); throw new FaultException<CurrencyExchangeException> (new CurrencyExchangeException(StringsResource.FailedToContactCurrencyExchange + " " + ex.Message, ex)); } finally { var channel = currencyProx as ICommunicationObject; if ((channel != null) && (channel.State == CommunicationState.Opened)) channel.Close(); channel = currencyAsmxProx as ICommunicationObject; if ((channel != null) && (channel.State == CommunicationState.Opened)) channel.Close(); } }
public void PayForTicket(Guid orderID, Guid payingCustomerID, double amount, PaymentType methodOfPayment, Currencies? currency, Guid callID, string creditCard) { try { callback_prox = CallBackChannelFactory.GetProxy(false); Payment payment = null; // Do the job and call back the ticketing bridge payment = generalTicketing.PayForTicket(orderID, payingCustomerID, amount, methodOfPayment, currency, creditCard); callback_prox.PaymentArrived(payment, callID); } catch (TicketingException tex) { LoggingManager.Logger.Log(LoggingCategory.Error, StringsResource.TicketingFailed + " " + tex.Message); throw new TicketingException(StringsResource.TicketingFailed + " " + tex.Message, tex); } catch (Exception ex) { LoggingManager.Logger.Log(LoggingCategory.Error, StringsResource.FailedToContactTicketingBridge + " " + ex.Message); throw new TicketingException(StringsResource.TicketingFailed + " " + ex.Message, ex); } finally { if ((callback_prox != null) && ((callback_prox as ICommunicationObject).State == CommunicationState.Opened)) (callback_prox as ICommunicationObject).Close(); } }
public Payment PayForTicket(Guid orderID, Guid payingCustomerID, double amount, PaymentType methodOfPayment, Currencies? currency, string creditCard) { ITicketingServiceOneWay prox = null; Guid callId = Guid.NewGuid(); try { // Find a proxy to the ticketing service (one way) prox = TicketingServiceOneWayProxyFactory.GetProxy(false); AutoResetEvent arrived = new AutoResetEvent(false); // Create a ResultPackage with a wait handle to wait on until a response arrives (on another channel) ResultPackage pack = new ResultPackage() { ResultArrived = arrived }; ResultsCache.Current.SetPackage(callId, pack); // Call the ticketing service via MSMQ channel on another thread. Action<ITicketingServiceOneWay> del = (p => p.PayForTicket(orderID, payingCustomerID, amount, methodOfPayment, currency, callId, creditCard)); del.BeginInvoke(prox, null, null); //Wait until result arrives arrived.WaitOne(timeout); Payment result = (Payment)ResultsCache.Current.GetResult(callId); ResultsCache.Current.ClearResult(callId); return result; } catch (Exception ex) { LoggingManager.Logger.Log(LoggingCategory.Error, StringsResource.FailedToContactTicketing + " " + ex.Message); throw new TicketingException(StringsResource.TicketingFailed + " " + ex.Message, ex); } finally { if ((prox != null) && ((prox as ICommunicationObject).State == CommunicationState.Opened)) (prox as ICommunicationObject).Close(); } }
/// <summary> /// Sell the currency /// </summary> /// <param name="curency"></param> /// <param name="amount">The amount in the specified currency</param> /// <returns>The amount in the common currency</returns> public double Sell(Currencies curency, double amount) { ExchangeRateDal dal = new ExchangeRateDal(); double rate = dal.GetRate(curency.ToString()); if (rate == 0) return amount; return amount / rate * (1 - Commission); ; }
public ForexTicker(int i, int j, Currencies underlying, Currencies currency) : this() { InitializeComponent(); Underlying = underlying; Currency = currency; Id = (i << 0) | (j << 16); m_isNormalized = CalculateNormalized(); if (TRACE_TICKS) m_stopwatch.Start(); }
public CurrencySimulated(Currencies cur_enum, RandomNormal rand, double r) { this.cur_enum = cur_enum; this.r = r; this.rforeign = 0.01 + 0.05 * rand.NextDouble(); this.sigma = 0.1; this.lastPrice = 1; this.lastDate = DateTime.MinValue; this.rand = rand; this.prices = new Dictionary<DateTime, double>(); }
private static string GetCurrencyText(Currencies currency) { switch (currency) { case Currencies.Usd: return App_GlobalResources.CurrencyResource.UsdCurrencyText; case Currencies.Rub: return App_GlobalResources.CurrencyResource.RubCurrencyText; default: return App_GlobalResources.CurrencyResource.NoNameText; } }
public static KeyValuePair<string, string> getCodeQuandl(Currencies currency) { switch (currency) { case Currencies.USD: return new KeyValuePair<string, string>("ECB", "EURUSD"); case Currencies.HKD: return new KeyValuePair<string, string>("ECB", "EURHKD"); case Currencies.GBP: return new KeyValuePair<string, string>("ECB", "EURGBP"); case Currencies.CHF: return new KeyValuePair<string, string>("ECB", "EURCHF"); default: return new KeyValuePair<string, string>(); } }
private Currencies ReadCurrencyFromXmlFile() { var currencies = new Currencies(); using (var xmlReader = XmlReader.Create(new StringReader(File.ReadAllText(FileName)))) { while (xmlReader.ReadToFollowing("Currency")) { xmlReader.MoveToFirstAttribute(); var name = xmlReader.Value; xmlReader.MoveToContent(); var val = xmlReader.ReadElementContentAsDouble(); currencies.CurrencyDictionary[name] = val; } } return currencies; }
public static Irate getIrateFromCurrency(Currencies c) { switch (c) { case Currencies.CHF: return Irate.LiborCHF; case Currencies.EUR: return Irate.Euribor; case Currencies.GBP: return Irate.LiborGBP; case Currencies.HKD: return Irate.Hibor; case Currencies.USD: return Irate.LiborUSD; default: return Irate.Euribor; } }
public double Sell(Currencies currency, double amount) { double res; try { using (prox = new AsmxExchange.CurrencyExchangeService()) { res = (prox.Sell(MapCurrency(currency), amount)); } } catch (Exception ex) { LoggingManager.Logger.Log(LoggingCategory.Error, StringsResource.FailedToContactCurrencyExchange + " " + ex.Message); throw new CurrencyExchangeException(StringsResource.FailedToContactCurrencyExchange + " " + ex.Message, ex); } return res; }
public static double get_irate_from_currency(Currencies c, DateTime date) { using (var context = new qpcptfaw()) { int irateid; if (c == Currencies.EUR) { irateid = 1; } else { var currencies = from curr in context.Assets.OfType<ForexDB>() where curr.forex == c select curr; irateid = currencies.First().RateDBId; } return getInterestRate(irateid, date); } }
public ActionResult DoPayment(string orderId, string description, Currencies? currency, decimal? price) { if (string.IsNullOrEmpty(orderId) || !price.HasValue || !currency.HasValue) { return RedirectToAction("Index", "Home"); } var url = PaylevenWebApp.GetPaymentUrl(new PaymentRequest { DisplayName = _displayName, OrderId = orderId, Description = description, PriceInCents = (int)(price.Value * 100), Currency = currency.Value, CallbackUri = CallBackUri }); return RedirectOrPrint(url); }
public static double convertToEuro(double price, Currencies currency, DateTime date, qpcptfaw context){ if (currency.Equals(Currencies.EUR)) return price; double rate = 1; bool isException = true; DateTime datelocal = date; while (isException) { try { rate = Access.getExchangeRate(currency, datelocal, context); isException = false; } catch (Exception) { datelocal = datelocal.AddDays(-1); } } return price/rate; }
/// <summary> /// Calculate a final price /// </summary> /// <param name="reductionCode">This code is used to classify customes and to find pricing rules appropriate for different kind of customers</param> /// <param name="policyName">The relevant group of rules</param> /// <param name="listPrice">The base price if the event</param> /// <param name="numberOfOrders">Numbers of tickes ordered</param> /// <param name="currency">Currency in which the price us shown to the client</param> /// <returns>The calculated price</returns> public virtual double CalculatePrice(int reductionCode, string policyName, int listPrice, int numberOfTickets, Currencies? currency) { IExchangeService exchangeProx; PricingRule[] rules = null; #region Call Pricing Rules service and calculate rules = GetRulesFromService(policyName); //If there are rules use them if ((rules != null) && (rules.Count() > 0)) { var effectiveRules = rules.Where(rl => ((rl.ReductionCode == reductionCode) || (rl.MinNumOfOrders <= numberOfTickets))).ToArray(); localResult = manager.CalculatePrice(effectiveRules, listPrice); } else localResult = listPrice; #endregion if (currency != null) { // wrap the channel creation exchangeProx = new CurrencyExchangeProxy(); //Use the currency exhange service to tranform the price to the required currency localResult = exchangeProx.Buy(currency.Value, localResult); } return localResult; }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { Currencies = _currencyService.GetCurrencies(); returnUrl = returnUrl ?? Url.Content("~/"); ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); if (ModelState.IsValid) { var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email }; var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { _logger.LogInformation("User created a new account with password."); var claims = new List <Claim>(); claims.Add(new Claim(ClaimTypes.Surname, Input.FirstName)); claims.Add(new Claim(ClaimTypes.GivenName, Input.LastName)); claims.Add(new Claim(ClaimTypes.MobilePhone, Input.PhoneNumber)); user = await _userManager.FindByEmailAsync(Input.Email); await _userManager.AddClaimsAsync(user, claims); var organisation = new Organsation { BussinessRegistrationNumber = "", Contact = new Contact { PhoneNumber = Input.PhoneNumber, Address = "", ContactName = Input.FirstName + " " + Input.LastName, Email = Input.Email, Website = "", Id = Guid.NewGuid().ToString() }, DeclareTax = Input.TaxDeclare, LegalLocalName = Input.OrganisationDisplayName, LegalName = Input.OrganisationDisplayName, Description = "", DisplayName = Input.OrganisationDisplayName, LineBusiness = "", LogoUrl = "", OrganisationTypeId = 1, TaxNumber = "", OrganisationBaseCurrency = new OrganisationBaseCurrency { BaseCurrencyId = Input.BaseCurrencyId, TaxCurrencyId = Input.BaseCurrencyId } }; var baseCurrency = Currencies.FirstOrDefault(u => u.Id == Input.BaseCurrencyId); if (Input.TaxDeclare && baseCurrency.Code != "KHR") { organisation.OrganisationBaseCurrency.TaxCurrencyId = Currencies.FirstOrDefault(u => u.Code == "KHR").Id; organisation.OrganisationBaseCurrency.TaxExchangeRate = 4000; } _organisationService.Create(organisation, user.Id); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl }, protocol: Request.Scheme); await _emailSender.SendEmailAsync(Input.Email, "Confirm your email", $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.", true); if (_userManager.Options.SignIn.RequireConfirmedAccount) { return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl })); } else { await _signInManager.SignInAsync(user, isPersistent : false); return(LocalRedirect(returnUrl)); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return(Page()); }
private static string ToPayfortAmount(decimal amount, Currencies currency) => decimal.ToInt64(amount * PayfortConstants.ExponentMultipliers[currency]).ToString();
protected override TimedQuote getQuote(Currencies source, Currencies dest, ConversionBag convStatus) { return(quotes[source][dest]); }
public static decimal Truncate(decimal target, Currencies currency) => Math.Round(target, currency.GetDecimalDigitsCount(), MidpointRounding.ToZero);
/// <remarks/> public void BuyAsync(Currencies currency, double amount) { this.BuyAsync(currency, amount, null); }
public virtual void Patch(StoreEntity target) { if (target == null) { throw new ArgumentNullException(nameof(target)); } target.AdminEmail = AdminEmail; target.Catalog = Catalog; target.Country = Country; target.DefaultCurrency = DefaultCurrency; target.DefaultLanguage = DefaultLanguage; target.Description = Description; target.DisplayOutOfStock = DisplayOutOfStock; target.Email = Email; target.ModifiedBy = ModifiedBy; target.ModifiedDate = ModifiedDate; target.Name = Name; target.Region = Region; target.SecureUrl = SecureUrl; target.TimeZone = TimeZone; target.Url = Url; target.StoreState = (int)StoreState; target.FulfillmentCenterId = FulfillmentCenterId; target.ReturnsFulfillmentCenterId = ReturnsFulfillmentCenterId; if (!Languages.IsNullCollection()) { var languageComparer = AnonymousComparer.Create((StoreLanguageEntity x) => x.LanguageCode); Languages.Patch(target.Languages, languageComparer, (sourceLang, targetLang) => targetLang.LanguageCode = sourceLang.LanguageCode); } if (!Currencies.IsNullCollection()) { var currencyComparer = AnonymousComparer.Create((StoreCurrencyEntity x) => x.CurrencyCode); Currencies.Patch(target.Currencies, currencyComparer, (sourceCurrency, targetCurrency) => targetCurrency.CurrencyCode = sourceCurrency.CurrencyCode); } if (!TrustedGroups.IsNullCollection()) { var trustedGroupComparer = AnonymousComparer.Create((StoreTrustedGroupEntity x) => x.GroupName); TrustedGroups.Patch(target.TrustedGroups, trustedGroupComparer, (sourceGroup, targetGroup) => sourceGroup.GroupName = targetGroup.GroupName); } if (!PaymentMethods.IsNullCollection()) { var paymentComparer = AnonymousComparer.Create((StorePaymentMethodEntity x) => x.Code); PaymentMethods.Patch(target.PaymentMethods, paymentComparer, (sourceMethod, targetMethod) => sourceMethod.Patch(targetMethod)); } if (!ShippingMethods.IsNullCollection()) { var shippingComparer = AnonymousComparer.Create((StoreShippingMethodEntity x) => x.Code); ShippingMethods.Patch(target.ShippingMethods, shippingComparer, (sourceMethod, targetMethod) => sourceMethod.Patch(targetMethod)); } if (!FulfillmentCenters.IsNullCollection()) { var fulfillmentCenterComparer = AnonymousComparer.Create((StoreFulfillmentCenterEntity fc) => $"{fc.FulfillmentCenterId}-{fc.Type}"); FulfillmentCenters.Patch(target.FulfillmentCenters, fulfillmentCenterComparer, (sourceFulfillmentCenter, targetFulfillmentCenter) => sourceFulfillmentCenter.Patch(targetFulfillmentCenter)); } }
public double CalculateSalesPriceFromEuro(Currencies currency, double priceb) { this.pricec = CurrencyConverter.ConvertFromEuroTo(currency, priceb); return(this.pricec); }
public CurrencyInfo(Currencies currency) { switch (currency) { case Currencies.Syria: CurrencyID = 0; CurrencyCode = "SYP"; IsCurrencyNameFeminine = true; EnglishCurrencyName = "Egypt Pound"; EnglishPluralCurrencyName = "Egypt Pounds"; EnglishCurrencyPartName = "Piaster"; EnglishPluralCurrencyPartName = "Piasteres"; Arabic1CurrencyName = "جنيه مصرى"; Arabic2CurrencyName = "جنيهان مصريان"; Arabic310CurrencyName = "جنيهات مصرية"; Arabic1199CurrencyName = "جنيه مصرى"; Arabic1CurrencyPartName = "قرش"; Arabic2CurrencyPartName = "قرشان"; Arabic310CurrencyPartName = "قروش"; Arabic1199CurrencyPartName = "قرشاً"; PartPrecision = 2; IsCurrencyPartNameFeminine = false; break; case Currencies.UAE: CurrencyID = 1; CurrencyCode = "AED"; IsCurrencyNameFeminine = false; EnglishCurrencyName = "UAE Dirham"; EnglishPluralCurrencyName = "UAE Dirhams"; EnglishCurrencyPartName = "Fils"; EnglishPluralCurrencyPartName = "Fils"; Arabic1CurrencyName = "درهم إماراتي"; Arabic2CurrencyName = "درهمان إماراتيان"; Arabic310CurrencyName = "دراهم إماراتية"; Arabic1199CurrencyName = "درهماً إماراتياً"; Arabic1CurrencyPartName = "فلس"; Arabic2CurrencyPartName = "فلسان"; Arabic310CurrencyPartName = "فلوس"; Arabic1199CurrencyPartName = "فلساً"; PartPrecision = 2; IsCurrencyPartNameFeminine = false; break; case Currencies.SaudiArabia: CurrencyID = 2; CurrencyCode = "SAR"; IsCurrencyNameFeminine = false; EnglishCurrencyName = "Saudi Riyal"; EnglishPluralCurrencyName = "Saudi Riyals"; EnglishCurrencyPartName = "Halala"; EnglishPluralCurrencyPartName = "Halalas"; Arabic1CurrencyName = "ريال سعودي"; Arabic2CurrencyName = "ريالان سعوديان"; Arabic310CurrencyName = "ريالات سعودية"; Arabic1199CurrencyName = "ريالاً سعودياً"; Arabic1CurrencyPartName = "هللة"; Arabic2CurrencyPartName = "هللتان"; Arabic310CurrencyPartName = "هللات"; Arabic1199CurrencyPartName = "هللة"; PartPrecision = 2; IsCurrencyPartNameFeminine = true; break; case Currencies.Tunisia: CurrencyID = 3; CurrencyCode = "TND"; IsCurrencyNameFeminine = false; EnglishCurrencyName = "Tunisian Dinar"; EnglishPluralCurrencyName = "Tunisian Dinars"; EnglishCurrencyPartName = "milim"; EnglishPluralCurrencyPartName = "millimes"; Arabic1CurrencyName = "درهم إماراتي"; Arabic2CurrencyName = "درهمان إماراتيان"; Arabic310CurrencyName = "دراهم إماراتية"; Arabic1199CurrencyName = "درهماً إماراتياً"; Arabic1CurrencyPartName = "فلس"; Arabic2CurrencyPartName = "فلسان"; Arabic310CurrencyPartName = "فلوس"; Arabic1199CurrencyPartName = "فلساً"; PartPrecision = 3; IsCurrencyPartNameFeminine = false; break; case Currencies.Gold: CurrencyID = 4; CurrencyCode = "XAU"; IsCurrencyNameFeminine = false; EnglishCurrencyName = "Gram"; EnglishPluralCurrencyName = "Grams"; EnglishCurrencyPartName = "Milligram"; EnglishPluralCurrencyPartName = "Milligrams"; Arabic1CurrencyName = "جرام"; Arabic2CurrencyName = "جرامان"; Arabic310CurrencyName = "جرامات"; Arabic1199CurrencyName = "جراماً"; Arabic1CurrencyPartName = "ملجرام"; Arabic2CurrencyPartName = "ملجرامان"; Arabic310CurrencyPartName = "ملجرامات"; Arabic1199CurrencyPartName = "ملجراماً"; PartPrecision = 2; IsCurrencyPartNameFeminine = false; break; } }
public static Task <IEnumerable <BalanceError> > CheckBalancesAsync( IAccount account, IEnumerable <WalletAddress> addresses, CancellationToken cancellationToken = default) { return(Task.Run(async() => { try { var errors = new List <BalanceError>(); foreach (var address in addresses) { var actualBalance = 0m; if (Currencies.IsTezosToken(address.Currency)) { // tezos tokens var xtzConfig = account.Currencies.Get <TezosConfig>("XTZ"); var fa12Config = account.Currencies.Get <Fa12Config>(address.Currency); var bcdSettings = xtzConfig.BcdApiSettings; var bcdApi = new BcdApi(bcdSettings); var balanceResult = await bcdApi .GetTokenBalancesAsync( address: address.Address, contractAddress: fa12Config.TokenContractAddress, cancellationToken: cancellationToken) .ConfigureAwait(false); if (balanceResult == null || balanceResult.HasError || balanceResult.Value == null || !balanceResult.Value.Any()) { errors.Add(new BalanceError { Type = BalanceErrorType.FailedToGet, Address = address.Address, LocalBalance = address.AvailableBalance(), }); continue; } actualBalance = balanceResult.Value.First().GetTokenBalance(); } else if (Currencies.IsEthereumToken(address.Currency)) { // ethereum tokens var erc20 = account.Currencies .Get <Erc20Config>(address.Currency); var api = erc20.BlockchainApi as IEthereumBlockchainApi; var balanceResult = await api .TryGetErc20BalanceAsync( address: address.Address, contractAddress: erc20.ERC20ContractAddress, cancellationToken: cancellationToken) .ConfigureAwait(false); if (balanceResult == null || balanceResult.HasError) { errors.Add(new BalanceError { Type = BalanceErrorType.FailedToGet, Address = address.Address, LocalBalance = address.AvailableBalance(), }); continue; } actualBalance = erc20.TokenDigitsToTokens(balanceResult.Value); } else { var api = account.Currencies .GetByName(address.Currency) .BlockchainApi; var balanceResult = await api .TryGetBalanceAsync( address: address.Address, cancellationToken: cancellationToken) .ConfigureAwait(false); if (balanceResult == null || balanceResult.HasError) { errors.Add(new BalanceError { Type = BalanceErrorType.FailedToGet, Address = address.Address, LocalBalance = address.AvailableBalance(), }); continue; } actualBalance = balanceResult.Value; } if (actualBalance < address.AvailableBalance()) { errors.Add(new BalanceError { Type = BalanceErrorType.LessThanExpected, Address = address.Address, LocalBalance = address.AvailableBalance(), ActualBalance = actualBalance }); } else if (actualBalance > address.AvailableBalance() && Currencies.IsBitcoinBased(address.Currency)) { errors.Add(new BalanceError { Type = BalanceErrorType.MoreThanExpected, Address = address.Address, LocalBalance = address.AvailableBalance(), ActualBalance = actualBalance }); } } return errors; } catch (Exception e) { Log.Error(e, "Balance check error"); } return addresses.Select(a => new BalanceError { Type = BalanceErrorType.FailedToGet, Address = a.Address, LocalBalance = a.AvailableBalance() }); }, cancellationToken)); }
/// <summary> /// Returns a <see cref="string"/> that represents the current <see cref="Cash"/>. /// </summary> /// <returns>A <see cref="string"/> that represents the current <see cref="Cash"/>.</returns> public string ToString(string accountCurrency) { // round the conversion rate for output var rate = ConversionRate; rate = rate < 1000 ? rate.RoundToSignificantDigits(5) : Math.Round(rate, 2); return(Invariant($"{Symbol}: {CurrencySymbol}{Amount,15:0.00} @ {rate,10:0.00####} = {Currencies.GetCurrencySymbol(accountCurrency)}{Math.Round(ValueInAccountCurrency, 2)}")); }
public void Dispose() { Currencies.SetProvider(() => null); }
public RegisterCurrencies(CurrencyCollection instance) { _instance = instance; Currencies.SetProvider(() => _instance); }
public Money(decimal Amount, Currencies currency) { this.Amount = Amount; this.AmountGeneral = Amount * ConvertCoefficent(currency); this.currency = currency; }
/// <summary> /// Ensures that we have a data feed to convert this currency into the base currency. /// This will add a <see cref="SubscriptionDataConfig"/> and create a <see cref="Security"/> at the lowest resolution if one is not found. /// </summary> /// <param name="securities">The security manager</param> /// <param name="subscriptions">The subscription manager used for searching and adding subscriptions</param> /// <param name="marketMap">The market map that decides which market the new security should be in</param> /// <param name="changes">Will be used to consume <see cref="SecurityChanges.AddedSecurities"/></param> /// <param name="securityService">Will be used to create required new <see cref="Security"/></param> /// <param name="accountCurrency">The account currency</param> /// <param name="defaultResolution">The default resolution to use for the internal subscriptions</param> /// <returns>Returns the added <see cref="SubscriptionDataConfig"/>, otherwise null</returns> public List <SubscriptionDataConfig> EnsureCurrencyDataFeed(SecurityManager securities, SubscriptionManager subscriptions, IReadOnlyDictionary <SecurityType, string> marketMap, SecurityChanges changes, ISecurityService securityService, string accountCurrency, Resolution defaultResolution = Resolution.Minute ) { // this gets called every time we add securities using universe selection, // so must of the time we've already resolved the value and don't need to again if (CurrencyConversion != null) { return(null); } if (Symbol == accountCurrency) { _isBaseCurrency = true; CurrencyConversion = null; ConversionRate = 1.0m; return(null); } // existing securities var securitiesToSearch = securities.Select(kvp => kvp.Value) .Concat(changes.AddedSecurities) .Where(s => s.Type == SecurityType.Forex || s.Type == SecurityType.Cfd || s.Type == SecurityType.Crypto); // Create a SecurityType to Market mapping with the markets from SecurityManager members var markets = securities.Select(x => x.Key) .GroupBy(x => x.SecurityType) .ToDictionary(x => x.Key, y => y.Select(symbol => symbol.ID.Market).ToHashSet()); if (markets.ContainsKey(SecurityType.Cfd) && !markets.ContainsKey(SecurityType.Forex)) { markets.Add(SecurityType.Forex, markets[SecurityType.Cfd]); } if (markets.ContainsKey(SecurityType.Forex) && !markets.ContainsKey(SecurityType.Cfd)) { markets.Add(SecurityType.Cfd, markets[SecurityType.Forex]); } var forexEntries = GetAvailableSymbolPropertiesDatabaseEntries(SecurityType.Forex, marketMap, markets); var cfdEntries = GetAvailableSymbolPropertiesDatabaseEntries(SecurityType.Cfd, marketMap, markets); var cryptoEntries = GetAvailableSymbolPropertiesDatabaseEntries(SecurityType.Crypto, marketMap, markets); var potentialEntries = forexEntries .Concat(cfdEntries) .Concat(cryptoEntries) .ToList(); if (!potentialEntries.Any(x => Symbol == x.Key.Symbol.Substring(0, x.Key.Symbol.Length - x.Value.QuoteCurrency.Length) || Symbol == x.Value.QuoteCurrency)) { // currency not found in any tradeable pair Log.Error($"No tradeable pair was found for currency {Symbol}, conversion rate to account currency ({accountCurrency}) will be set to zero."); CurrencyConversion = null; ConversionRate = 0m; return(null); } // Special case for crypto markets without direct pairs (They wont be found by the above) // This allows us to add cash for "StableCoins" that are 1-1 with our account currency without needing a conversion security. // Check out the StableCoinsWithoutPairs static var for those that are missing their 1-1 conversion pairs if (marketMap.TryGetValue(SecurityType.Crypto, out var market) && (Currencies.IsStableCoinWithoutPair(Symbol + accountCurrency, market) || Currencies.IsStableCoinWithoutPair(accountCurrency + Symbol, market))) { CurrencyConversion = null; ConversionRate = 1.0m; return(null); } var requiredSecurities = new List <SubscriptionDataConfig>(); var potentials = potentialEntries .Select(x => QuantConnect.Symbol.Create(x.Key.Symbol, x.Key.SecurityType, x.Key.Market)); var minimumResolution = subscriptions.Subscriptions.Select(x => x.Resolution).DefaultIfEmpty(defaultResolution).Min(); var makeNewSecurity = new Func <Symbol, Security>(symbol => { var securityType = symbol.ID.SecurityType; // use the first subscription defined in the subscription manager var type = subscriptions.LookupSubscriptionConfigDataTypes(securityType, minimumResolution, false).First(); var objectType = type.Item1; var tickType = type.Item2; // set this as an internal feed so that the data doesn't get sent into the algorithm's OnData events var config = subscriptions.SubscriptionDataConfigService.Add(symbol, minimumResolution, fillForward: true, extendedMarketHours: false, isInternalFeed: true, subscriptionDataTypes: new List <Tuple <Type, TickType> > { new Tuple <Type, TickType>(objectType, tickType) }).First(); var newSecurity = securityService.CreateSecurity(symbol, config, addToSymbolCache: false); Log.Trace($"Cash.EnsureCurrencyDataFeed(): Adding {symbol.Value} for cash {Symbol} currency feed"); securities.Add(symbol, newSecurity); requiredSecurities.Add(config); return(newSecurity); }); CurrencyConversion = SecurityCurrencyConversion.LinearSearch(Symbol, accountCurrency, securitiesToSearch.ToList(), potentials, makeNewSecurity); return(requiredSecurities); }
public int Save(Currencies Data) { TopContractsV01Entities context = new TopContractsV01Entities(Utilities.getTestEnvName()); TopContractsEntities.Currency efCurrency = null; foreach (TopContractsDAL10.SystemTables.Currency Currency in Data.Entries) { if (Currency.New) { efCurrency = new TopContractsEntities.Currency(); } else { efCurrency = context.Currencies.Where(c => c.CurrencyID == Currency.ID).SingleOrDefault(); } if (Currency.Deleted == false) { efCurrency.InitCommonFields(efCurrency, Currency, efCurrency.CurrenciesLNGs, this.organizationIdentifier); efCurrency.Rate = Currency.Rate; efCurrency.RateDate = Currency.RateDate; } if (Currency.New) { context.Currencies.Add(efCurrency); } else { if (Currency.Deleted && efCurrency != null) { efCurrency.DeleteLanguageEntries(efCurrency, context.CurrenciesLNGs, efCurrency.CurrenciesLNGs); //for (int indx = efCurrency.CurrenciesLNGs.Count() - 1; indx >= 0; indx--) //{ // TopContractsEntities.CurrenciesLNG lng = efCurrency.CurrenciesLNGs.ElementAt(indx); // context.CurrenciesLNGs.Remove(lng); //} context.Currencies.Remove(efCurrency); } } } return context.SaveChanges(); }
public MsnMoneyV2CurrencyExchangeService() { BaseCurrency = Currencies.First(x => x.Name == "US Dollar"); }
public static DateTime GetLastData(Currencies currency) { using (var context = new qpcptfaw()) { double l; int id = getForexIdFromCurrency(currency); var rates = from p in context.Prices where p.AssetDBId == id select p; if (rates.Count() == 0) return DBInitialisation.DBstart; return rates.OrderByDescending(x => x.date).First().date; } }
public void CalculateSalesPriceFromEuro(Currencies currency) { this.SalesPrice = CurrencyConverter.ConvertFromEuroTo(currency, salespriceInEuro); this.PurchasePrice = CurrencyConverter.ConvertFromEuroTo(currency, purchasepriceInEuro); }
/*public static List<Currencies> getAllCurrencies() { using (var context = new qpcptfaw()) { List<Currencies> list_res = new List<Currencies>(); var currencies = from f in context.Forex select f; if (currencies.Count() == 0) throw new Exception("No currencies stored in the database"); foreach (var c in currencies) list_res.Add(c.currency); return list_res; } }*/ public static bool CurrenciesContains(Currencies c) { using (var context = new qpcptfaw()) { var currencies = from f in context.Assets.OfType<ForexDB>() where f.forex == c select f; if (currencies.Count() == 1) return true; if (currencies.Count() == 0) return false; throw new Exception("The data should be unique. Problem in the database."); } }
public static decimal ToEven(decimal target, Currencies currency) => Math.Round(target, currency.GetDecimalDigitsCount(), MidpointRounding.ToEven);
public static double getExchangeRate(Currencies currency, DateTime date, qpcptfaw context) { int cid; if (_id_forex.ContainsKey(currency)) { cid = _id_forex[currency]; } else { cid = getForexIdFromCurrency(currency); _id_forex.Add(currency, cid); } var rates = from r in context.Prices where r.AssetDBId == cid && r.date == date select r; if (rates.Count() == 0) throw new ArgumentException("No data for this date and currency", date.ToString()); if (rates.Count() > 1) throw new Exception("The data required should be unique."); return rates.First().price; }
/// <remarks/> public void BuyAsync(Currencies currency, double amount, object userState) { if ((this.BuyOperationCompleted == null)) { this.BuyOperationCompleted = new System.Threading.SendOrPostCallback(this.OnBuyOperationCompleted); } this.InvokeAsync("Buy", new object[] { currency, amount}, this.BuyOperationCompleted, userState); }
/////JsonResult Function To AjaxRequestController////////////////// //public JsonResult GetFlightClassCodeByAirline(int id) //{ // var result = new JsonResult(); // var lists = new SelectList(_tfareprovider.GetFlightClassCodeByAirlineID(id), "DomesticFlightClassId", "FlightClassCode"); // result.Data = lists; // result.JsonRequestBehavior = JsonRequestBehavior.AllowGet; // return result; //} //public JsonResult GetAirlines(int AirlineTypeId) //{ // var model = _provider.GetAirlinesList(AirlineTypeId).ToList(); // JsonResult result = new JsonResult(); // result.Data = new SelectList(model, "AirlineId", "AirlineName"); // result.JsonRequestBehavior = JsonRequestBehavior.AllowGet; // return result; //} //public JsonResult GetCities(int AirlineTypeId) //{ // var model = _provider.CityListAsperFlightType(AirlineTypeId).ToList(); // JsonResult result = new JsonResult(); // result.Data = new SelectList(model, "CityID", "CityName"); // result.JsonRequestBehavior = JsonRequestBehavior.AllowGet; // return result; //} #region Custom region public void SetValueForDropdownlist() { var flightclasslist = ent.Air_DomesticFlightClasses.ToList(); Air_DomesticFlightClasses flightclassSelect = new Air_DomesticFlightClasses() { DomesticFlightClassId = -1, FlightClassCode = "--Select--" }; flightclasslist.Insert(0, flightclassSelect); var currencylist = ent.Currencies.ToList(); Currencies currencySelect = new Currencies() { CurrencyId = -1, CurrencyName = "--Select--" }; currencylist.Insert(0, currencySelect); //var flighttypelist = ent.FlightTypes.ToList(); //FlightTypes flighttypeSelect = new FlightTypes() { FlightTypeId = -1, FlightTypeName ="--Select--" }; //flighttypelist.Insert(0, flighttypeSelect); var flightsessionlist = ent.FlightSeasons.ToList(); FlightSeasons flightsessionSelect = new FlightSeasons { FlightSeasonId = -1, FlightSeasonName = "--Select--" }; flightsessionlist.Insert(0, flightsessionSelect); //var airlinelist = ent.Airlines.ToList(); //Airlines airlineSelect = new Airlines() { AirlineId = -1, AirlineName = "--Select--" }; //airlinelist.Insert(0, airlineSelect); //var departurecitylist = ent.AirlineCities.ToList(); //AirlineCities departurecitylistSelect = new AirlineCities() { CityID = -1, CityName = "--Select--" }; //departurecitylist.Insert(0, departurecitylistSelect); //var destinationcitylist = ent.AirlineCities.ToList(); //AirlineCities destinartioncitySelect = new AirlineCities() { CityID = -1, CityName = "--Select--" }; //destinationcitylist.Insert(0, destinartioncitySelect); //ViewData["FlightClasses"] = flightclasslist;//new SelectList(_tfareprovider.GetAllFlightClass(), "FlightClassId", "FlightClassCode"); //ViewData["CurrencyType"] = currencylist;//new SelectList(_tfareprovider.GetAllCurrencyType(), "CurrencyId", "CurrencyCode"); //ViewData["FlightTypes"] = flighttypelist;//new SelectList(_tfareprovider.GetAllFlightType(), "FlightTypeId", "FlightTypeName"); //ViewData["FlightSeasons"] = flightsessionlist;//new SelectList(_tfareprovider.GetAllFlightSeason(), "FlightSeasonId", "FlightSeasonName"); //ViewData["Airline"] = airlinelist;//new SelectList(_tfareprovider.GetAllAirline(), "AirlineId", "AirlineName"); //ViewData["DepartureCity"] = departurecitylist;//new SelectList(_tfareprovider.GetAllAirlineCity(), "CityID", "CityName"); //ViewData["DestinationCity"] = departurecitylist; //new SelectList(_tfareprovider.GetAllAirlineCity(), "CityID", "CityName"); ViewData["FlightClasses"] = new SelectList(_tfareprovider.GetAllFlightClass(), "FlightClassId", "FlightClassCode"); ViewData["CurrencyType"] = new SelectList(_tfareprovider.GetAllCurrencyType(), "CurrencyId", "CurrencyCode"); ViewData["FlightTypes"] = new SelectList(_tfareprovider.GetDomesticFlightType(), "FlightTypeId", "FlightTypeName", 0); ViewData["FlightSeasons"] = new SelectList(_tfareprovider.GetAllFlightSeason(), "FlightSeasonId", "FlightSeasonName"); ViewData["Airline"] = new SelectList(_tfareprovider.GetAllDomesticAirlines(), "AirlineId", "AirlineName", 0); ViewData["DepartureCity"] = new SelectList(_tfareprovider.GetDomesticCities(), "CityID", "CityName", 0); // ViewData["DestinationCity"] = new SelectList(_tfareprovider.GetAllAirlineCity(), "CityID", "CityName"); ViewData["ChildFairTypes"] = new SelectList(ATLTravelPortal.Helpers.ChildFairTypes.GetChildFairType(), "ChildFairTypeID", "ChildFairType", "P"); ViewData["ChildFairOns"] = new SelectList(ATLTravelPortal.Helpers.ChildFairOns.GetChildFairOn(), "ChildFairOnId", "ChildFairOnss", "M"); }
public static decimal Ceil(decimal target, Currencies currency) => Math.Round(target, currency.GetDecimalDigitsCount(), MidpointRounding.AwayFromZero);
public Cost(Currencies.Potion potionCost) { _Cost.Potion = potionCost; }
public Cost(Currencies.Coin coinCost, Currencies.Potion potionCost, Boolean special, Boolean canOverpay) : this(coinCost, potionCost) { _Special = special; _CanOverpay = canOverpay; }
public static Dictionary<string, double> convertToEuro(Dictionary<string, double> prices, Currencies currency, DateTime date, qpcptfaw context) { if (currency.Equals(Currencies.EUR)) return prices; Dictionary<string, double> p_converti = new Dictionary<string, double>(); double rate = 1; bool isException = true; DateTime datelocal = date; while (isException && datelocal>=DBInitialisation.DBstart) { try { rate = Access.getExchangeRate(currency, datelocal, context); isException = false; } catch (Exception) { datelocal = datelocal.AddDays(-1); } } if (datelocal < DBInitialisation.DBstart) { rate = Access.getFirstExchangeRate(currency, context); } foreach (KeyValuePair<string,double> p in prices) { p_converti.Add(p.Key, p.Value / rate); } return p_converti; }
public static new Currency GetBySymbol(Currencies symbol) { return(Crypto.GetBySymbolAndNetwork((CryptoCurrencies)symbol)); }
public void Execute() { var singleton = this.Session.GetSingleton(); var dutchLocale = new Locales(this.Session).DutchNetherlands; singleton.AddAdditionalLocale(dutchLocale); var euro = new Currencies(this.Session).FindBy(M.Currency.IsoCode, "EUR"); var be = new Countries(this.Session).FindBy(M.Country.IsoCode, "BE"); var us = new Countries(this.Session).FindBy(M.Country.IsoCode, "US"); var email2 = new EmailAddressBuilder(this.Session) .WithElectronicAddressString("*****@*****.**") .Build(); var allorsLogo = this.DataPath + @"\www\admin\images\logo.png"; var allors = Organisations.CreateInternalOrganisation( session: this.Session, name: "Allors BVBA", address: "Kleine Nieuwedijkstraat 4", postalCode: "2800", locality: "Mechelen", country: be, phone1CountryCode: "+32", phone1: "2 335 2335", phone1Purpose: new ContactMechanismPurposes(this.Session).GeneralPhoneNumber, phone2CountryCode: string.Empty, phone2: string.Empty, phone2Purpose: null, emailAddress: "*****@*****.**", websiteAddress: "www.allors.com", taxNumber: "BE 0476967014", bankName: "ING", facilityName: "Allors Warehouse 1", bic: "BBRUBEBB", iban: "BE89 3200 1467 7685", currency: euro, logo: allorsLogo, storeName: "Allors Store", billingProcess: new BillingProcesses(this.Session).BillingForOrderItems, outgoingShipmentNumberPrefix: "a-CS", salesInvoiceNumberPrefix: "a-SI", salesOrderNumberPrefix: "a-SO", requestNumberPrefix: "a-RFQ", quoteNumberPrefix: "a-Q", productNumberPrefix: "A-", requestCounterValue: 1, quoteCounterValue: 1, orderCounterValue: 1, invoiceCounterValue: 1); var dipu = Organisations.CreateInternalOrganisation( session: this.Session, name: "Dipu BVBA", address: "Kleine Nieuwedijkstraat 2", postalCode: "2800", locality: "Mechelen", country: be, phone1CountryCode: "+32", phone1: "2 15 49 49 49", phone1Purpose: new ContactMechanismPurposes(this.Session).GeneralPhoneNumber, phone2CountryCode: string.Empty, phone2: string.Empty, phone2Purpose: null, emailAddress: "*****@*****.**", websiteAddress: "www.dipu.com", taxNumber: "BE 0445366489", bankName: "ING", facilityName: "Dipu Facility", bic: "BBRUBEBB", iban: "BE23 3300 6167 6391", currency: euro, logo: allorsLogo, storeName: "Dipu Store", billingProcess: new BillingProcesses(this.Session).BillingForOrderItems, outgoingShipmentNumberPrefix: "d-CS", salesInvoiceNumberPrefix: "d-SI", salesOrderNumberPrefix: "d-SO", requestNumberPrefix: "d-RFQ", quoteNumberPrefix: "d-Q", productNumberPrefix: "D-", requestCounterValue: 1, quoteCounterValue: 1, orderCounterValue: 1, invoiceCounterValue: 1); singleton.Settings.DefaultFacility = allors.FacilitiesWhereOwner.First; this.SetupUser(allors, "*****@*****.**", "first", "allors employee", "letmein"); this.SetupUser(dipu, "*****@*****.**", "first", "dipu employee", "letmein"); new FacilityBuilder(this.Session) .WithName("Allors warehouse 2") .WithFacilityType(new FacilityTypes(this.Session).Warehouse) .WithOwner(allors) .Build(); var manufacturer = new OrganisationBuilder(this.Session).WithName("Gizmo inc.").WithIsManufacturer(true).Build(); var productType = new ProductTypeBuilder(this.Session) .WithName($"Gizmo") .WithSerialisedItemCharacteristicType(new SerialisedItemCharacteristicTypeBuilder(this.Session) .WithName("Size") .WithLocalisedName(new LocalisedTextBuilder(this.Session).WithText("Afmeting").WithLocale(dutchLocale).Build()) .Build()) .WithSerialisedItemCharacteristicType(new SerialisedItemCharacteristicTypeBuilder(this.Session) .WithName("Weight") .WithLocalisedName(new LocalisedTextBuilder(this.Session).WithText("Gewicht").WithLocale(dutchLocale).Build()) .WithUnitOfMeasure(new UnitsOfMeasure(this.Session).Kilogram) .Build()) .Build(); var vatRate = new VatRateBuilder(this.Session).WithRate(21).Build(); var brand = new BrandBuilder(this.Session) .WithName("brand1") .WithModel(new ModelBuilder(this.Session).WithName("model1").Build()) .Build(); var finishedGood = new NonUnifiedPartBuilder(this.Session) .WithProductIdentification(new SkuIdentificationBuilder(this.Session) .WithIdentification("10101") .WithProductIdentificationType(new ProductIdentificationTypes(this.Session).Sku).Build()) .WithName("finished good") .WithBrand(brand) .WithModel(brand.Models[0]) .WithInventoryItemKind(new InventoryItemKinds(this.Session).NonSerialised) .WithManufacturedBy(manufacturer) .Build(); var good1 = new NonUnifiedGoodBuilder(this.Session) .WithProductIdentification(new ProductNumberBuilder(this.Session) .WithIdentification("G1") .WithProductIdentificationType(new ProductIdentificationTypes(this.Session).Good).Build()) .WithName("Tiny blue round gizmo") .WithLocalisedName(new LocalisedTextBuilder(this.Session).WithText("Zeer kleine blauwe ronde gizmo").WithLocale(dutchLocale).Build()) .WithDescription("Perfect blue with nice curves") .WithLocalisedDescription(new LocalisedTextBuilder(this.Session).WithText("Perfect blauw met mooie rondingen").WithLocale(dutchLocale).Build()) .WithVatRate(vatRate) .WithPart(finishedGood) .Build(); new InventoryItemTransactionBuilder(this.Session) .WithPart(finishedGood) .WithFacility(allors.FacilitiesWhereOwner.First) .WithQuantity(100) .WithReason(new InventoryTransactionReasons(this.Session).Unknown) .Build(); var finishedGood2 = new NonUnifiedPartBuilder(this.Session) .WithName("finished good2") .WithInventoryItemKind(new InventoryItemKinds(this.Session).Serialised) .WithProductType(productType) .WithProductIdentification(new SkuIdentificationBuilder(this.Session) .WithIdentification("10102") .WithProductIdentificationType(new ProductIdentificationTypes(this.Session).Sku).Build()) .WithManufacturedBy(manufacturer) .Build(); var good2 = new NonUnifiedGoodBuilder(this.Session) .WithProductIdentification(new ProductNumberBuilder(this.Session) .WithIdentification("G2") .WithProductIdentificationType(new ProductIdentificationTypes(this.Session).Good).Build()) .WithName("Tiny red round gizmo") .WithLocalisedName(new LocalisedTextBuilder(this.Session).WithText("Zeer kleine rode ronde gizmo").WithLocale(dutchLocale).Build()) .WithDescription("Perfect red with nice curves") .WithLocalisedDescription(new LocalisedTextBuilder(this.Session).WithText("Perfect rood met mooie rondingen").WithLocale(dutchLocale).Build()) .WithVatRate(vatRate) .WithPart(finishedGood2) .Build(); var serialisedItem = new SerialisedItemBuilder(this.Session).WithSerialNumber("1").WithAvailableForSale(true).Build(); finishedGood2.AddSerialisedItem(serialisedItem); new InventoryItemTransactionBuilder(this.Session) .WithSerialisedItem(serialisedItem) .WithFacility(allors.FacilitiesWhereOwner.First) .WithQuantity(1) .WithReason(new InventoryTransactionReasons(this.Session).IncomingShipment) .WithSerialisedInventoryItemState(new SerialisedInventoryItemStates(this.Session).Available) .Build(); var finishedGood3 = new NonUnifiedPartBuilder(this.Session) .WithProductIdentification(new SkuIdentificationBuilder(this.Session) .WithIdentification("10103") .WithProductIdentificationType(new ProductIdentificationTypes(this.Session).Sku).Build()) .WithName("finished good3") .WithInventoryItemKind(new InventoryItemKinds(this.Session).NonSerialised) .WithManufacturedBy(manufacturer) .Build(); var good3 = new NonUnifiedGoodBuilder(this.Session) .WithProductIdentification(new ProductNumberBuilder(this.Session) .WithIdentification("G3") .WithProductIdentificationType(new ProductIdentificationTypes(this.Session).Good).Build()) .WithName("Tiny green round gizmo") .WithLocalisedName(new LocalisedTextBuilder(this.Session).WithText("Zeer kleine groene ronde gizmo").WithLocale(dutchLocale).Build()) .WithDescription("Perfect red with nice curves") .WithLocalisedDescription(new LocalisedTextBuilder(this.Session).WithText("Perfect groen met mooie rondingen").WithLocale(dutchLocale).Build()) .WithVatRate(vatRate) .WithPart(finishedGood3) .Build(); var finishedGood4 = new NonUnifiedPartBuilder(this.Session) .WithName("finished good4") .WithInventoryItemKind(new InventoryItemKinds(this.Session).Serialised) .WithProductType(productType) .WithManufacturedBy(manufacturer) .Build(); var good4 = new NonUnifiedGoodBuilder(this.Session) .WithProductIdentification(new ProductNumberBuilder(this.Session) .WithIdentification("G4") .WithProductIdentificationType(new ProductIdentificationTypes(this.Session).Good).Build()) .WithName("Tiny purple round gizmo") .WithLocalisedName(new LocalisedTextBuilder(this.Session).WithText("Zeer kleine paarse ronde gizmo").WithLocale(dutchLocale).Build()) .WithVatRate(vatRate) .WithPart(finishedGood4) .Build(); var productCategory1 = new ProductCategoryBuilder(this.Session) .WithInternalOrganisation(allors) .WithName("Best selling gizmo's") .WithLocalisedName(new LocalisedTextBuilder(this.Session).WithText("Meest verkochte gizmo's").WithLocale(dutchLocale).Build()) .Build(); var productCategory2 = new ProductCategoryBuilder(this.Session) .WithInternalOrganisation(allors) .WithName("Big Gizmo's") .WithLocalisedName(new LocalisedTextBuilder(this.Session).WithText("Grote Gizmo's").WithLocale(dutchLocale).Build()) .Build(); var productCategory3 = new ProductCategoryBuilder(this.Session) .WithInternalOrganisation(allors) .WithName("Small gizmo's") .WithLocalisedName(new LocalisedTextBuilder(this.Session).WithText("Kleine gizmo's").WithLocale(dutchLocale).Build()) .WithProduct(good1) .WithProduct(good2) .WithProduct(good3) .WithProduct(good4) .Build(); new CatalogueBuilder(this.Session) .WithInternalOrganisation(allors) .WithName("New gizmo's") .WithLocalisedName(new LocalisedTextBuilder(this.Session).WithText("Nieuwe gizmo's").WithLocale(dutchLocale).Build()) .WithDescription("Latest in the world of Gizmo's") .WithLocalisedDescription(new LocalisedTextBuilder(this.Session).WithText("Laatste in de wereld van Gizmo's").WithLocale(dutchLocale).Build()) .WithProductCategory(productCategory1) .Build(); this.Session.Derive(); for (int i = 0; i < 100; i++) { var acmePostalAddress = new PostalAddressBuilder(this.Session) .WithAddress1($"Acme{i} address 1") .WithPostalBoundary(new PostalBoundaryBuilder(this.Session).WithLocality($"Acme{i} city").WithPostalCode("1111").WithCountry(us).Build()) .Build(); var acmeBillingAddress = new PartyContactMechanismBuilder(this.Session) .WithContactMechanism(acmePostalAddress) .WithContactPurpose(new ContactMechanismPurposes(this.Session).GeneralCorrespondence) .WithUseAsDefault(true) .Build(); var acmeInquiries = new PartyContactMechanismBuilder(this.Session) .WithContactMechanism(new TelecommunicationsNumberBuilder(this.Session).WithCountryCode("+1").WithContactNumber("111 222 333").Build()) .WithContactPurpose(new ContactMechanismPurposes(this.Session).GeneralPhoneNumber) .WithContactPurpose(new ContactMechanismPurposes(this.Session).OrderInquiriesPhone) .WithUseAsDefault(true) .Build(); var acme = new OrganisationBuilder(this.Session) .WithName($"Acme{i}") .WithLocale(new Locales(this.Session).EnglishUnitedStates) .WithPartyContactMechanism(acmeBillingAddress) .WithPartyContactMechanism(acmeInquiries) .WithTaxNumber($"{1000 + i}-{1000 + i}-{1000 + i}") .Build(); var contact1Email = new PartyContactMechanismBuilder(this.Session) .WithContactMechanism(new EmailAddressBuilder(this.Session).WithElectronicAddressString($"employee1@acme{i}.com").Build()) .WithContactPurpose(new ContactMechanismPurposes(this.Session).PersonalEmailAddress) .WithUseAsDefault(true) .Build(); var contact2PhoneNumber = new PartyContactMechanismBuilder(this.Session) .WithContactMechanism(new TelecommunicationsNumberBuilder(this.Session).WithCountryCode("+1").WithAreaCode("123").WithContactNumber("456").Build()) .WithContactPurpose(new ContactMechanismPurposes(this.Session).GeneralPhoneNumber) .WithUseAsDefault(true) .Build(); var contact1 = new PersonBuilder(this.Session) .WithFirstName($"John{i}") .WithLastName($"Doe{i}") .WithGender(new GenderTypes(this.Session).Male) .WithLocale(new Locales(this.Session).EnglishUnitedStates) .WithPartyContactMechanism(contact1Email) .Build(); var contact2 = new PersonBuilder(this.Session) .WithFirstName($"Jane{i}") .WithLastName($"Doe{i}") .WithGender(new GenderTypes(this.Session).Male) .WithLocale(new Locales(this.Session).EnglishUnitedStates) .WithPartyContactMechanism(contact2PhoneNumber) .Build(); new CustomerRelationshipBuilder(this.Session) .WithCustomer(acme) .WithInternalOrganisation(allors) .WithFromDate(DateTime.UtcNow) .Build(); new OrganisationContactRelationshipBuilder(this.Session) .WithOrganisation(acme) .WithContact(contact1) .WithContactKind(new OrganisationContactKinds(this.Session).FindBy(M.OrganisationContactKind.Description, "General contact")) .WithFromDate(DateTime.UtcNow) .Build(); new OrganisationContactRelationshipBuilder(this.Session) .WithOrganisation(acme) .WithContact(contact2) .WithContactKind(new OrganisationContactKinds(this.Session).FindBy(M.OrganisationContactKind.Description, "General contact")) .WithFromDate(DateTime.UtcNow) .Build(); var administrator = (Person) new UserGroups(this.Session).Administrators.Members.First; new FaceToFaceCommunicationBuilder(this.Session) .WithDescription($"Meeting {i}") .WithSubject($"meeting {i}") .WithEventPurpose(new CommunicationEventPurposes(this.Session).Meeting) .WithFromParty(contact1) .WithToParty(contact2) .WithOwner(administrator) .WithActualStart(DateTime.UtcNow) .Build(); new EmailCommunicationBuilder(this.Session) .WithDescription($"Email {i}") .WithSubject($"email {i}") .WithFromEmail(email2) .WithToEmail(email2) .WithEventPurpose(new CommunicationEventPurposes(this.Session).Meeting) .WithOwner(administrator) .WithActualStart(DateTime.UtcNow) .Build(); new LetterCorrespondenceBuilder(this.Session) .WithDescription($"Letter {i}") .WithSubject($"letter {i}") .WithFromParty(administrator) .WithToParty(contact1) .WithEventPurpose(new CommunicationEventPurposes(this.Session).Meeting) .WithOwner(administrator) .WithActualStart(DateTime.UtcNow) .Build(); new PhoneCommunicationBuilder(this.Session) .WithDescription($"Phone {i}") .WithSubject($"phone {i}") .WithFromParty(administrator) .WithToParty(contact1) .WithEventPurpose(new CommunicationEventPurposes(this.Session).Meeting) .WithOwner(administrator) .WithActualStart(DateTime.UtcNow) .Build(); var requestForQuote = new RequestForQuoteBuilder(this.Session) .WithEmailAddress($"customer{i}@acme.com") .WithTelephoneNumber("+1 234 56789") .WithRecipient(allors) .Build(); var requestItem = new RequestItemBuilder(this.Session) .WithSerialisedItem(serialisedItem) .WithProduct(serialisedItem.PartWhereSerialisedItem.NonUnifiedGoodsWherePart.FirstOrDefault()) .WithComment($"Comment {i}") .WithQuantity(1) .Build(); requestForQuote.AddRequestItem(requestItem); var productQuote = new ProductQuoteBuilder(this.Session) .WithIssuer(allors) .WithReceiver(acme) .WithFullfillContactMechanism(acmePostalAddress) .Build(); var quoteItem = new QuoteItemBuilder(this.Session) .WithSerialisedItem(serialisedItem) .WithProduct(serialisedItem.PartWhereSerialisedItem.NonUnifiedGoodsWherePart.FirstOrDefault()) .WithComment($"Comment {i}") .WithQuantity(1) .Build(); productQuote.AddQuoteItem(quoteItem); var salesOrderItem1 = new SalesOrderItemBuilder(this.Session) .WithDescription("first item") .WithProduct(good1) .WithActualUnitPrice(3000) .WithQuantityOrdered(1) .WithMessage(@"line1 line2") .WithInvoiceItemType(new InvoiceItemTypes(this.Session).ProductItem) .Build(); var salesOrderItem2 = new SalesOrderItemBuilder(this.Session) .WithDescription("second item") .WithActualUnitPrice(2000) .WithQuantityOrdered(2) .WithInvoiceItemType(new InvoiceItemTypes(this.Session).ProductItem) .Build(); var salesOrderItem3 = new SalesOrderItemBuilder(this.Session) .WithDescription("Fee") .WithActualUnitPrice(100) .WithQuantityOrdered(1) .WithInvoiceItemType(new InvoiceItemTypes(this.Session).Fee) .Build(); var order = new SalesOrderBuilder(this.Session) .WithTakenBy(allors) .WithBillToCustomer(acme) .WithBillToEndCustomerContactMechanism(acmeBillingAddress.ContactMechanism) .WithSalesOrderItem(salesOrderItem1) .WithSalesOrderItem(salesOrderItem2) .WithSalesOrderItem(salesOrderItem3) .WithCustomerReference("a reference number") .WithDescription("Sale of 1 used Aircraft Towbar") .WithVatRegime(new VatRegimes(this.Session).Assessable) .Build(); var salesInvoiceItem1 = new SalesInvoiceItemBuilder(this.Session) .WithDescription("first item") .WithProduct(good1) .WithActualUnitPrice(3000) .WithQuantity(1) .WithMessage(@"line1 line2") .WithInvoiceItemType(new InvoiceItemTypes(this.Session).ProductItem) .Build(); var salesInvoiceItem2 = new SalesInvoiceItemBuilder(this.Session) .WithDescription("second item") .WithActualUnitPrice(2000) .WithQuantity(2) .WithInvoiceItemType(new InvoiceItemTypes(this.Session).ProductItem) .Build(); var salesInvoiceItem3 = new SalesInvoiceItemBuilder(this.Session) .WithDescription("Fee") .WithActualUnitPrice(100) .WithQuantity(1) .WithInvoiceItemType(new InvoiceItemTypes(this.Session).Fee) .Build(); var exw = new IncoTermTypes(this.Session).Exw; var incoTerm = new IncoTermBuilder(this.Session).WithTermType(exw).WithTermValue("XW").Build(); var salesInvoice = new SalesInvoiceBuilder(this.Session) .WithBilledFrom(allors) .WithBillToCustomer(acme) .WithBillToContactPerson(contact1) .WithBillToContactMechanism(acme.PartyContactMechanisms[0].ContactMechanism) .WithBillToEndCustomerContactMechanism(acmeBillingAddress.ContactMechanism) .WithShipToContactPerson(contact2) .WithSalesInvoiceItem(salesInvoiceItem1) .WithSalesInvoiceItem(salesInvoiceItem2) .WithSalesInvoiceItem(salesInvoiceItem3) .WithCustomerReference("a reference number") .WithDescription("Sale of 1 used Aircraft Towbar") .WithSalesInvoiceType(new SalesInvoiceTypes(this.Session).SalesInvoice) .WithSalesTerm(incoTerm) .WithVatRegime(new VatRegimes(this.Session).Assessable) .Build(); for (var j = 0; j < 30; j++) { var salesInvoiceItem = new SalesInvoiceItemBuilder(this.Session) .WithDescription("Extra Charge") .WithActualUnitPrice(100 + j) .WithQuantity(j) .WithInvoiceItemType(new InvoiceItemTypes(this.Session).MiscCharge) .Build(); salesInvoice.AddSalesInvoiceItem(salesInvoiceItem); } } for (int i = 0; i < 4; i++) { var supplierPostalAddress = new PostalAddressBuilder(this.Session) .WithAddress1($"Supplier{i} address 1") .WithPostalBoundary(new PostalBoundaryBuilder(this.Session).WithLocality($"Supplier{i} city").WithPostalCode("1111").WithCountry(us).Build()) .Build(); var supplierBillingAddress = new PartyContactMechanismBuilder(this.Session) .WithContactMechanism(supplierPostalAddress) .WithContactPurpose(new ContactMechanismPurposes(this.Session).GeneralCorrespondence) .WithUseAsDefault(true) .Build(); var supplier = new OrganisationBuilder(this.Session) .WithName($"Supplier{i}") .WithLocale(new Locales(this.Session).EnglishUnitedStates) .WithPartyContactMechanism(supplierBillingAddress) .Build(); new SupplierRelationshipBuilder(this.Session) .WithSupplier(supplier) .WithInternalOrganisation(allors) .WithFromDate(DateTime.UtcNow) .Build(); var purchaseInvoiceItem1 = new PurchaseInvoiceItemBuilder(this.Session) .WithDescription("first item") .WithPart(finishedGood) .WithActualUnitPrice(3000) .WithQuantity(1) .WithMessage(@"line1 line2") .WithInvoiceItemType(new InvoiceItemTypes(this.Session).PartItem) .Build(); var purchaseInvoiceItem2 = new PurchaseInvoiceItemBuilder(this.Session) .WithDescription("second item") .WithActualUnitPrice(2000) .WithQuantity(2) .WithPart(finishedGood2) .WithInvoiceItemType(new InvoiceItemTypes(this.Session).PartItem) .Build(); var purchaseInvoiceItem3 = new PurchaseInvoiceItemBuilder(this.Session) .WithDescription("Fee") .WithActualUnitPrice(100) .WithQuantity(1) .WithInvoiceItemType(new InvoiceItemTypes(this.Session).Fee) .Build(); var purchaseInvoice = new PurchaseInvoiceBuilder(this.Session) .WithBilledTo(allors) .WithBilledFrom(supplier) .WithPurchaseInvoiceItem(purchaseInvoiceItem1) .WithPurchaseInvoiceItem(purchaseInvoiceItem2) .WithPurchaseInvoiceItem(purchaseInvoiceItem3) .WithCustomerReference("a reference number") .WithDescription("Purchase of 1 used Aircraft Towbar") .WithPurchaseInvoiceType(new PurchaseInvoiceTypes(this.Session).PurchaseInvoice) .WithVatRegime(new VatRegimes(this.Session).Assessable) .Build(); var purchaseOrderItem1 = new PurchaseOrderItemBuilder(this.Session) .WithDescription("first purchase order item") .WithPart(finishedGood) .WithQuantityOrdered(1) .Build(); var purchaseOrder = new PurchaseOrderBuilder(this.Session) .WithOrderedBy(allors) .WithTakenViaSupplier(supplier) .WithPurchaseOrderItem(purchaseOrderItem1) .WithCustomerReference("a reference number") .Build(); } var acme0 = new Organisations(this.Session).FindBy(M.Organisation.Name, "Acme0"); var item = new SerialisedItemBuilder(this.Session) .WithSerialNumber("112") .WithSerialisedItemState(new SerialisedItemStates(this.Session).Sold) .WithAvailableForSale(false) .WithOwnedBy(acme0) .Build(); finishedGood2.AddSerialisedItem(item); var worktask = new WorkTaskBuilder(this.Session) .WithTakenBy(allors) .WithCustomer(new Organisations(this.Session).FindBy(M.Organisation.Name, "Acme0")) .WithName("maintenance") .Build(); new WorkEffortFixedAssetAssignmentBuilder(this.Session) .WithFixedAsset(item) .WithAssignment(worktask) .Build(); this.Session.Derive(); }
public static double GetCurrencyExchangeWithEuro(Currencies currency, DateTime date) { using (var context = new qpcptfaw()) { int id = getForexIdFromCurrency(currency); int limit = 7; for(int i=0; i<limit; i++) { var rates = from p1 in context.Prices where p1.AssetDBId == id && p1.date == date select p1; if (rates.Count() > 0) { return rates.First().priceEur; } else { date = date - TimeSpan.FromDays(1); } } throw new ArgumentOutOfRangeException("No data for this date"); } }
public void Register_Known_Currencies() { Currencies.Initialize(EUR, USD); }
public static int getForexIdFromCurrency(Currencies c) { int id = -1; using (var context = new qpcptfaw()) { var a = from currency in context.Assets.OfType<ForexDB>() where currency.forex == c select currency; if (a.Count() == 0) throw new ArgumentException("symbol does not exist in the database", c.ToString()); if (a.Count() > 1) throw new ArgumentException("duplicate symbol in the database", c.ToString()); id = a.First().AssetDBId; return id; } }
public void Use_Default_Provider_When_Set() { var sut = Currencies.SetRegionInfoProvider(); sut.Count.Should().BeGreaterThan(10); }
/// <summary> /// ///////////////////////////////////////////////////////////////////////////// /// </summary> /// <param name="currency"></param> /// <param name="context"></param> /// <returns></returns> public static double getFirstExchangeRate(Currencies currency, qpcptfaw context) { int cid; if (_id_forex.ContainsKey(currency)) { cid = _id_forex[currency]; } else { cid = getForexIdFromCurrency(currency); _id_forex.Add(currency, cid); } var rates = from r in context.Prices where r.AssetDBId == cid select r; return rates.OrderBy(x => x.date).First().price; }
public void Registering_Null_Throws_ArgumentNullException() { Action action = () => Currencies.SetProvider(null); action.Should().Throw <ArgumentNullException>(); }
public Cost(Currencies.Coin coinCost) { _Cost.Coin = coinCost; }
public void Initialize_Returns_An_Instance_With_The_Given_Currencies() { var sut = Currencies.Initialize(EUR, USD); sut.Count.Should().Be(2); }
public Cost(Currencies.Coin coinCost, Currencies.Potion potionCost) : this(coinCost) { _Cost.Potion = potionCost; }
public CurrenciesPage(Currencies currencies, ObservableCollection <Currency> bindableCurrencies) { Title = "Currencies"; WrappedCurrencies = new List <WrappedCurrency>(); BindableCurrencies = bindableCurrencies; bindableCurrencies.Clear(); foreach (var currency in currencies.currencies) { bool isSelected = false; if (currencies.defaultCurrencies.Contains(currency.Name)) { isSelected = true; bindableCurrencies.Add(currency); } WrappedCurrencies.Add(new WrappedCurrency() { Currency = currency, IsSelected = isSelected }); } var stackLayout = new StackLayout(); ListView mainList = new ListView() { ItemsSource = WrappedCurrencies, ItemTemplate = new DataTemplate(typeof(WrappedCurrencySelectionTemplate)), }; mainList.ItemSelected += (sender, e) => { if (e.SelectedItem == null) { return; } var o = (WrappedCurrency)e.SelectedItem; o.IsSelected = !o.IsSelected; ((ListView)sender).SelectedItem = null; //de-select }; var searchBar = new SearchBar { Placeholder = "Filter by", VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.FillAndExpand, BindingContext = ViewModel }; searchBar.SetBinding <CurrenciesViewModel>(SearchBar.TextProperty, vm => vm.SearchBarText, BindingMode.TwoWay); searchBar.TextChanged += (sender, e) => { if (string.IsNullOrEmpty(searchBar.Text) || string.IsNullOrWhiteSpace(searchBar.Text)) { mainList.ItemsSource = WrappedCurrencies; } else { searchBar.Text = searchBar.Text.ToUpper(); mainList.ItemsSource = WrappedCurrencies. Where(wrappedCurrency => wrappedCurrency.Currency.Name.Contains(searchBar.Text)).ToList(); } }; stackLayout.Children.Add(mainList); stackLayout.Children.Add(searchBar); Content = stackLayout; if (Device.OS == TargetPlatform.Windows) { // fix issue where rows are badly sized (as tall as the screen) on WinPhone8.1 mainList.RowHeight = 40; // also need icons for Windows app bar (other platforms can just use text) ToolbarItems.Add(new ToolbarItem("All", "check.png", SelectAll, ToolbarItemOrder.Primary)); ToolbarItems.Add(new ToolbarItem("None", "cancel.png", SelectNone, ToolbarItemOrder.Primary)); } else { ToolbarItems.Add(new ToolbarItem("All", null, SelectAll, ToolbarItemOrder.Primary)); ToolbarItems.Add(new ToolbarItem("None", null, SelectNone, ToolbarItemOrder.Primary)); } }
public void SetCurrency(Currencies currency) { CurrencyName = Enum.GetName(typeof(Currencies), (int)currency); CurrencyValue = (int)currency; }
public void Fill() { // Fill database only first time - there is no need to fill it every user's request if (!_firstFill) { return; } _firstFill = false; Accounts.RemoveRange(Accounts); AccountTypes.RemoveRange(AccountTypes); Categories.RemoveRange(Categories); Counterparts.RemoveRange(Counterparts); Currencies.RemoveRange(Currencies); LoanTypes.RemoveRange(LoanTypes); Transactions.RemoveRange(Transactions); TransactionTypes.RemoveRange(TransactionTypes); Icons.RemoveRange(Icons); SaveChanges(); var accountTypes = new List <AccountType> { new AccountType { Title = "Наличные" }, new AccountType { Title = "Кредитная карта" }, new AccountType { Title = "Дебитовая карта" }, }; AddRange(accountTypes); var currencies = new List <Currency> { new Currency { Title = "Рубли", Symbol = "₽" }, new Currency { Title = "Доллары", Symbol = "$" }, new Currency { Title = "Евро", Symbol = "€" }, new Currency { Title = "Юани", Symbol = "¥" }, new Currency { Title = "Гривны", Symbol = "₴" }, }; AddRange(currencies); var accountTitles = new List <string> { "Тинькофф рубли", "Сбербанк", "Наличные доллары", "Юани оставшиеся с поездки", }; var accounts = Enumerable.Range(1, GetRandomValue(15)).Select(index => { return(new Account { AccountType = accountTypes.GetAny(), Currency = currencies.GetAny(), Title = accountTitles.GetAny() }); }); AddRange(accounts); // TODO: there are much more icons in TempData file var icons = TempData.Icons.Take(20).Select(icon => new Icon { Tag = icon }); AddRange(icons); var categories = new List <Category> { new Category { Title = "Свободные", Icon = icons.GetAny() }, new Category { Title = "Продукты", Icon = icons.GetAny() }, new Category { Title = "Здоровье", Icon = icons.GetAny() }, new Category { Title = "Дети", Icon = icons.GetAny() }, new Category { Title = "Животные", Icon = icons.GetAny() }, new Category { Title = "Автомобиль", Icon = icons.GetAny() }, }; AddRange(categories); var loanTypes = new List <LoanType> { new LoanType { Title = "Мне дали/Мне вернули" }, new LoanType { Title = "Я дал/Я вернул" }, }; AddRange(loanTypes); var transactionTypes = new List <TransactionType> { new TransactionType { Id = 1, Title = "Расход" }, new TransactionType { Id = 2, Title = "Приход" }, new TransactionType { Id = 3, Title = "Перевод между счетами" }, new TransactionType { Id = 4, Title = "Долг" }, }; AddRange(transactionTypes); var counterparts = new List <Counterpart> { new Counterpart { Title = "Пятерочка" }, new Counterpart { Title = "Дядя Сережа" }, new Counterpart { Title = "Петька" }, new Counterpart { Title = "ООО Рога и копыта" }, new Counterpart { Title = "ИП Мясников Николай Иванович" }, new Counterpart { Title = "ИП Овчинников А.П." }, new Counterpart { Title = "Сбербанк" }, new Counterpart { Title = "Билайн" }, new Counterpart { Title = "ОАО Кольцово" }, new Counterpart { Title = "ПАО Энергосбыт" }, }; AddRange(counterparts); var transactions = Enumerable.Range(1, GetRandomValue(1000)).Select(index => { var transaction = new Transaction { Account = accounts.GetAny(), Amount = GetRandomValue(10000), Category = categories.GetAny(), Counterpart = counterparts.GetAny(), Date = DateTime.Now.AddMinutes(new Random().Next(-100000, 0)), TransactionType = transactionTypes.GetAny(), }; if (transaction.TransactionType.Title.Equals("Долг")) { transaction.LoanType = loanTypes.GetAny(); } return(transaction); }); AddRange(transactions); SaveChanges(); }
public Payment PayForTicket(Guid orderID, Guid payingCustomerID, double amount, PaymentType methodOfPayment, Currencies? currency, string creditCard) { IPaymentService paymentProx = null; IExchangeService exchangeProx = null; Payment paymentConfirmation; //validate order var order = manager.FindOrder(orderID); if (order == null) throw new TicketingException(StringsResource.NullOrder); if ((order.State == OrderState.Approved) && (amount > 0)) throw new TicketingException(StringsResource.OrderAlreadyApproved); if (currency != null) { exchangeProx = new CurrencyExchangeWcfProxy.CurrencyExchangeProxy(); amount = Math.Round(exchangeProx.Buy(currency.Value, amount), 1); } #region call the payment service //call the payment service lock (this) { if (paymentChf == null) paymentChf = new ChannelFactory<IPaymentService>("CertPaymentEP"); } try { paymentProx = paymentChf.CreateChannel(); paymentConfirmation = paymentProx.PayForOrder(orderID, payingCustomerID, amount, methodOfPayment, creditCard); } catch (Exception ex) { LoggingManager.Logger.Log(LoggingCategory.Error, ex.Message); throw new TicketingException(StringsResource.FailedToContactPayment + " " + ex.Message, ex); } finally { var channel = paymentProx as ICommunicationObject; if ((channel != null) && (channel.State == CommunicationState.Opened)) channel.Close(); } #endregion //save the payment in the order; order.PaymentsInfo.Add(paymentConfirmation); double totalpayments = 0; foreach (var item in order.PaymentsInfo) totalpayments += item.Amount; if ((totalpayments >= order.TotalPrice) && (order.State != OrderState.Approved)) { order.State = OrderState.Approved; manager.UpdateOrder(order); } if ((amount < 0) && (order.State == OrderState.Approved)) { order.State = OrderState.Created; manager.UpdateOrder(order); } return paymentConfirmation; }
public CurrencyInfo(Currencies currency) { switch (currency) { case Currencies.Jo: CurrencyID = 0; CurrencyCode = "JOD"; IsCurrencyNameFeminine = false; EnglishCurrencyName = "JOD Dienar"; EnglishPluralCurrencyName = "JOD penny"; EnglishCurrencyPartName = "Fils"; EnglishPluralCurrencyPartName = "Fils"; Arabic1CurrencyName = "دينار اردني"; Arabic2CurrencyName = "ديناران اردني"; Arabic310CurrencyName = "دنانير اردنية"; Arabic1199CurrencyName = "ديناراً اردني"; Arabic1CurrencyPartName = "فلس"; Arabic2CurrencyPartName = "فلسان"; Arabic310CurrencyPartName = "فلوس"; Arabic1199CurrencyPartName = "فلساً"; PartPrecision = 2; IsCurrencyPartNameFeminine = false; break; case Currencies.Syria: CurrencyID = 5; CurrencyCode = "SYP"; IsCurrencyNameFeminine = true; EnglishCurrencyName = "Syrian Pound"; EnglishPluralCurrencyName = "Syrian Pounds"; EnglishCurrencyPartName = "Piaster"; EnglishPluralCurrencyPartName = "Piasteres"; Arabic1CurrencyName = "ليرة سورية"; Arabic2CurrencyName = "ليرتان سوريتان"; Arabic310CurrencyName = "ليرات سورية"; Arabic1199CurrencyName = "ليرة سورية"; Arabic1CurrencyPartName = "قرش"; Arabic2CurrencyPartName = "قرشان"; Arabic310CurrencyPartName = "قروش"; Arabic1199CurrencyPartName = "قرشاً"; PartPrecision = 2; IsCurrencyPartNameFeminine = false; break; case Currencies.UAE: CurrencyID = 1; CurrencyCode = "AED"; IsCurrencyNameFeminine = false; EnglishCurrencyName = "UAE Dirham"; EnglishPluralCurrencyName = "UAE Dirhams"; EnglishCurrencyPartName = "Fils"; EnglishPluralCurrencyPartName = "Fils"; Arabic1CurrencyName = "درهم إماراتي"; Arabic2CurrencyName = "درهمان إماراتيان"; Arabic310CurrencyName = "دراهم إماراتية"; Arabic1199CurrencyName = "درهماً إماراتياً"; Arabic1CurrencyPartName = "فلس"; Arabic2CurrencyPartName = "فلسان"; Arabic310CurrencyPartName = "فلوس"; Arabic1199CurrencyPartName = "فلساً"; PartPrecision = 2; IsCurrencyPartNameFeminine = false; break; case Currencies.SaudiArabia: CurrencyID = 2; CurrencyCode = "SAR"; IsCurrencyNameFeminine = false; EnglishCurrencyName = "Saudi Riyal"; EnglishPluralCurrencyName = "Saudi Riyals"; EnglishCurrencyPartName = "Halala"; EnglishPluralCurrencyPartName = "Halalas"; Arabic1CurrencyName = "ريال سعودي"; Arabic2CurrencyName = "ريالان سعوديان"; Arabic310CurrencyName = "ريالات سعودية"; Arabic1199CurrencyName = "ريالاً سعودياً"; Arabic1CurrencyPartName = "هللة"; Arabic2CurrencyPartName = "هللتان"; Arabic310CurrencyPartName = "هللات"; Arabic1199CurrencyPartName = "هللة"; PartPrecision = 2; IsCurrencyPartNameFeminine = true; break; case Currencies.Tunisia: CurrencyID = 3; CurrencyCode = "TND"; IsCurrencyNameFeminine = false; EnglishCurrencyName = "Tunisian Dinar"; EnglishPluralCurrencyName = "Tunisian Dinars"; EnglishCurrencyPartName = "milim"; EnglishPluralCurrencyPartName = "millimes"; Arabic1CurrencyName = "دينار تونسي"; Arabic2CurrencyName = "ديناران تونسيان"; Arabic310CurrencyName = "دنانير تونسية"; Arabic1199CurrencyName = "ديناراً تونسياً"; Arabic1CurrencyPartName = "مليم"; Arabic2CurrencyPartName = "مليمان"; Arabic310CurrencyPartName = "ملاليم"; Arabic1199CurrencyPartName = "مليماً"; PartPrecision = 3; IsCurrencyPartNameFeminine = false; break; case Currencies.Gold: CurrencyID = 4; CurrencyCode = "XAU"; IsCurrencyNameFeminine = false; EnglishCurrencyName = "Gram"; EnglishPluralCurrencyName = "Grams"; EnglishCurrencyPartName = "Milligram"; EnglishPluralCurrencyPartName = "Milligrams"; Arabic1CurrencyName = "جرام"; Arabic2CurrencyName = "جرامان"; Arabic310CurrencyName = "جرامات"; Arabic1199CurrencyName = "جراماً"; Arabic1CurrencyPartName = "ملجرام"; Arabic2CurrencyPartName = "ملجرامان"; Arabic310CurrencyPartName = "ملجرامات"; Arabic1199CurrencyPartName = "ملجراماً"; PartPrecision = 2; IsCurrencyPartNameFeminine = false; break; } }
static public Money convert(Money money, Currencies targetCurrency) { return(new Money(money.Sum * rates[(int)money.Currency, (int)targetCurrency], targetCurrency)); }
public void Sell() { Currencies.AddGold(price); Destroy(gameObject); Selector.Deselect(); }