public CurrencyRate FindRateForDateOrBefore(CurrencyCodes currency, DateTime date) { return((from currencyRate in _db.CurrencyRates where currencyRate.BankDay.Date <= date.Date && currencyRate.Currency == currency orderby currencyRate.BankDay select currencyRate).LastOrDefault()); }
public static Currency Get(CurrencyCodes currencyCode) { if (CurrencyDictionary.ContainsKey(currencyCode)) return CurrencyDictionary[currencyCode]; else return null; }
private Dictionary <DateTime, decimal> ExtractRates(CurrencyCodes currency) { switch (currency) { case CurrencyCodes.EUR: var ddd = _db.CurrencyRates.Where(r => r.Currency == CurrencyCodes.EUR).OrderBy(r => r.BankDay); var di = new Dictionary <DateTime, decimal>(); foreach (var currencyRate in ddd) { if (di.ContainsKey(currencyRate.BankDay.Date)) { MessageBox.Show($"{currencyRate.BankDay.Date}"); } else { di.Add(currencyRate.BankDay.Date, (decimal)(1 / currencyRate.Rate)); } } return(di); case CurrencyCodes.BYR: return(_db.CurrencyRates.Where(r => r.Currency == CurrencyCodes.BYR).OrderBy(r => r.BankDay). ToDictionary(currencyRate => currencyRate.BankDay.Date, currencyRate => (decimal)currencyRate.Rate)); default: return(null); } }
/// <summary> /// The constructor /// </summary> /// <param name="total"></param> /// <param name="currencyCode"></param> /// <param name="subtotal"></param> /// <param name="eventTypes"></param> public OrderInfoOptions(decimal total, CurrencyCodes currencyCode, decimal subtotal, EventTypes eventTypes) { Total = total; CurrencyCode = currencyCode; Subtotal = subtotal; EventType = eventTypes; }
public async Task <double> BuyTransfers(double amount, CurrencyCodes currencyCode) { try { string partition = currencyCode.ToString(); string row = DateTime.Now.ToString("yyyy-MM-dd"); var exchange = await _azureTableStorage.RetrieveExchangeRateUsingPointQueryAsync(partition, row); var exchangerate = new { Multiplier = exchange.Multiplier, BuyTransfers = exchange.BuyTransfers }; if (exchangerate == null) { _log.LogError("Unable to get latest exchangerate for: {0} ", currencyCode.ToString()); throw new ArgumentException("Could not get the exchangerate for this currency"); } return(convert(exchangerate.Multiplier, amount, Convert.ToDouble(exchangerate.BuyTransfers))); } catch (Exception ex) { _log.LogError(ex.Message, ex); throw; } }
/// <summary> /// The constructor /// </summary> /// <param name="eventType"></param> /// <param name="eventStatus"></param> /// <param name="currencyCode"></param> /// <param name="total"></param> public PayInfoOptions(PayEventTypes eventType, EventStatuses eventStatus, CurrencyCodes currencyCode, decimal total) { EventType = eventType; EventStatus = eventStatus; CurrencyCode = currencyCode; Total = total; }
public decimal this[CurrencyCodes index] { get { var m = this.FirstOrDefault(c => c.Currency == index); return(m == null ? 0 : m.Amount); } }
public double GetRate(CurrencyCodes currency, DateTime day) { var rate = (from currencyRate in _db.CurrencyRates where currencyRate.BankDay.Date == day.Date && currencyRate.Currency == currency select currencyRate).FirstOrDefault(); return(rate != null ? rate.Rate : 0.0); }
public void Initialize(decimal totalAmount, CurrencyCodes currency, Account initialArticle) { Currency = currency; TotalAmount = totalAmount; PartialAmount = totalAmount; PartialArticle = initialArticle; ChangeAllProperties(); }
private Currency(CurrencyCodes currencyCode, CultureInfo cultureInfo) { CurrencyCode = currencyCode; Code = Enum.GetName(typeof(CurrencyCodes), CurrencyCode); NumberFormat = cultureInfo.NumberFormat; var region = new RegionInfo(cultureInfo.LCID); Symbol = region.CurrencySymbol; EnglishName = region.CurrencyEnglishName; }
public double GetRateThisDayOrBefore(CurrencyCodes currency, DateTime day) { var rate = (from currencyRate in _db.CurrencyRates where currencyRate.BankDay.Date <= day.Date && currencyRate.Currency == currency orderby currencyRate.BankDay select currencyRate).LastOrDefault(); return(rate != null ? rate.Rate : 0.0); }
public double GetLastRate(CurrencyCodes currency) { var rate = (from currencyRate in _db.CurrencyRates where currencyRate.Currency == currency orderby currencyRate.BankDay select currencyRate).LastOrDefault(); return(rate != null ? rate.Rate : 0.0); }
/// <summary> /// The constructor /// </summary> /// <param name="sharedKey">The private shared key from Visa</param> /// <param name="callId">The CallID value from VisaResponse.success</param> /// <param name="eventType">The event type of this transaction</param> /// <param name="apiKey">The public API Key from Visa</param> /// <param name="subtotal">The subtotal of the transaction</param> /// <param name="total">The total of the transaction</param> /// <param name="currencyCode">The currency code value</param> public VisaUpdateImageOptions(string sharedKey, string callId, EventTypes eventType, string apiKey, decimal subtotal, decimal total, CurrencyCodes currencyCode) { SharedKey = sharedKey; CallID = callId; EventType = eventType; ApiKey = apiKey; Subtotal = subtotal; Total = total; CurrencyCode = currencyCode; }
public static bool Exists(CurrencyCodes currencyCode) { if (CurrencyDictionary.ContainsKey(currencyCode)) return true; var cultureInfo = CultureInfoFromCurrencyISO(Enum.GetName(typeof (CurrencyCodes), currencyCode)); if(cultureInfo == null) return false; CurrencyDictionary.Add(currencyCode, new Currency(currencyCode, cultureInfo)); return true; }
/// <summary> /// Constructs a currency object with a NumberFormatInfo. /// </summary> /// <param name="currencyCode"></param> public Currency(CurrencyCodes currencyCode) { CurrencyCode = currencyCode; Code = Enum.GetName(typeof(CurrencyCodes), CurrencyCode); var cultureInfo = CultureInfoFromCurrencyISO(Code); NumberFormat = cultureInfo.NumberFormat; var region = new RegionInfo(cultureInfo.LCID); Symbol = region.CurrencySymbol; EnglishName = region.CurrencyEnglishName; }
public static Currency Get(CurrencyCodes currencyCode) { if (CurrencyDictionary.ContainsKey(currencyCode)) { return(CurrencyDictionary[currencyCode]); } else { return(null); } }
/// <summary> /// As an allowance or charge on item level, attaching it to the corresponding item. /// </summary> /// <param name="isDiscount">Marks if its an allowance (true) or charge (false). Please note that the xml will present inversed values</param> /// <param name="currency">Currency of the allowance or surcharge</param> /// <param name="basisAmount">Basis aount for the allowance or surcharge, typicalls the net amount of the item</param> /// <param name="actualAmount">The actual allowance or surcharge amount</param> /// <param name="reason">Reason for the allowance or surcharge</param> public void AddTradeAllowanceCharge(bool isDiscount, CurrencyCodes currency, decimal basisAmount, decimal actualAmount, string reason) { this.TradeAllowanceCharges.Add(new TradeAllowanceCharge() { ChargeIndicator = !isDiscount, Currency = currency, ActualAmount = actualAmount, BasisAmount = basisAmount, Reason = reason }); } // !AddTradeAllowanceCharge()
public static CurrencyCodes FromString(this CurrencyCodes _c, string s) { try { return((CurrencyCodes)Enum.Parse(typeof(CurrencyCodes), s)); } catch { return(CurrencyCodes.Unknown); } } // !FromString()
public Money Convert(CurrencyCodes toCurrency) { if (currencyCode == toCurrency) { return(this); } if (Converter == null) { throw new Exception("You need to assign an ICurrencyconverter to Money.Converter to automatically convert different currencies."); } return(Convert(toCurrency, Converter.GetRate(this.currencyCode, toCurrency, DateTime.Now))); }
/// <summary> /// Constructs a currency object with a NumberFormatInfo. /// </summary> /// <param name="currencyCode"></param> public Currency(CurrencyCodes currencyCode) { CurrencyCode = currencyCode; Code = Enum.GetName(typeof(CurrencyCodes), CurrencyCode); var cultureInfo = CultureInfoFromCurrencyISO(Code); if(cultureInfo == null) throw new Exception("Currency code " + Code + " is not supported by the current .Net Framework version."); NumberFormat = cultureInfo.NumberFormat; var region = new RegionInfo(cultureInfo.LCID); Symbol = region.CurrencySymbol; EnglishName = region.CurrencyEnglishName; }
private async void LoadCurrencyCodesAsync() { CurrencyCodes.Clear(); var newCurrencyCodes = await currencyCodeRepository.GetCurrencyCodes(); if (newCurrencyCodes != null) { foreach (var code in newCurrencyCodes) { CurrencyCodes.Add(code); } } }
protected virtual void Initialize(CurrencyCodes targetCurrencyCode) { // initialize currency _currencyExchangerRates.Add(CurrencyCodes.EUR, 1); _currencyExchangerRates.Add(CurrencyCodes.GBP, new decimal(0.84)); _currencyExchangerRates.Add(CurrencyCodes.USD, new decimal(1.40)); if (!_currencyExchangerRates.ContainsKey(targetCurrencyCode)) throw new NotSupportedException(string.Format("Currency code {0} in payload not supported or not ISO 4217 conform. Please chose one of following codes: {0}.", targetCurrencyCode.ToString(), _currencyExchangerRates.Keys.ToString())); this.Code = targetCurrencyCode.ToString(); this.ExchangeRate = _currencyExchangerRates[targetCurrencyCode]; }
protected virtual void Initialize(CurrencyCodes targetCurrencyCode) { // initialize currency _currencyExchangerRates.Add(CurrencyCodes.EUR, 1); _currencyExchangerRates.Add(CurrencyCodes.GBP, new decimal(0.84)); _currencyExchangerRates.Add(CurrencyCodes.USD, new decimal(1.40)); if (!_currencyExchangerRates.ContainsKey(targetCurrencyCode)) { throw new NotSupportedException(string.Format("Currency code {0} in payload not supported or not ISO 4217 conform. Please chose one of following codes: {0}.", targetCurrencyCode.ToString(), _currencyExchangerRates.Keys.ToString())); } this.Code = targetCurrencyCode.ToString(); this.ExchangeRate = _currencyExchangerRates[targetCurrencyCode]; }
private static string ProcentPredictionRepresentation(decimal amount, CurrencyCodes currency, decimal rate, Period period) { if (amount == 0) { return(currency == CurrencyCodes.USD ? "0 usd" : $"0 {currency.ToString().ToLower()} ($0)"); } if (currency == CurrencyCodes.USD) { return($"(за период {period.ToStringOnlyDates()}) {amount:#,0.00} usd"); } return(rate == 0 ? "не задан курс" : String.Format("(за период {4}) {0:#,0} {1} (по курсу {2} = ${3:#,0})", amount, currency.ToString().ToLower(), (int)rate, amount / rate, period.ToStringOnlyDates())); }
public decimal GetUsdEquivalent(decimal amount, CurrencyCodes currency, DateTime timestamp) { if (currency == CurrencyCodes.USD) { return(amount); } var rate = GetRateThisDayOrBefore(currency, timestamp); if (rate.Equals(0.0)) { return(-1); } return(amount / (decimal)rate); }
private Money ConvertOrCheck(CurrencyCodes toCurrency) { if (this.currencyCode == toCurrency) { return(this); } else if (AllowImplicitConversion) { return(this.Convert(toCurrency)); } else { throw new InvalidOperationException("Money type mismatch"); } }
public VisaOptions(string apiKey, decimal subTotal, CurrencyCodes currencyCode, OnOptions on) { InitOptions = new InitOptions { ApiKey = apiKey, PaymentRequest = new PaymentRequestOptions { CurrencyCode = currencyCode, Subtotal = subTotal } }; On = on; ButtonOptions = new ButtonOptions(); }
/// <summary> /// Хреново!!! - запрашивает остаток по всем валютам, и возращает по одной переданной в качестве параметра /// Иначе надо почти дублировать длинные AccountBalancePairs и ArticleBalancePairs, только с параметром валюта /// Если будет где-то тормозить, можно переписать /// </summary> /// <param name="account">счет, по которому будет вычислен остаток</param> /// <param name="period">период, за который учитываются обороты</param> /// <param name="currency">валюта, в которой учитываются обороты</param> /// <returns></returns> public decimal GetBalanceInCurrency(Account account, Period period, CurrencyCodes currency) { if (account == null) { return(0); } var balances = AccountBalancePairs(account, period); foreach (var balancePair in balances) { if (balancePair.Currency == currency) { return(balancePair.Amount); } } return(0); }
} // !AddLogisticsServiceCharge() public void AddTradeAllowanceCharge(bool isDiscount, decimal basisAmount, CurrencyCodes currency, decimal actualAmount, string reason, TaxTypes taxTypeCode, TaxCategoryCodes taxCategoryCode, decimal taxPercent) { this.TradeAllowanceCharges.Add(new TradeAllowanceCharge() { ChargeIndicator = !isDiscount, Reason = reason, BasisAmount = basisAmount, ActualAmount = actualAmount, Currency = currency, Amount = actualAmount, Tax = new Tax() { CategoryCode = taxCategoryCode, TypeCode = taxTypeCode, Percent = taxPercent } }); } // !AddTradeAllowanceCharge()
public string GetUsdEquivalentString(decimal amount, CurrencyCodes currency, DateTime timestamp, out decimal amountInUsd) { amountInUsd = 0; var rate = GetRate(currency, timestamp); if (rate.Equals(0.0)) { return("не задан курс " + currency + " на эту дату"); } amountInUsd = amount / (decimal)rate; var res = amountInUsd.ToString("F2", new CultureInfo("ru-Ru")) + "$ по курсу " + rate.ToString(new CultureInfo("ru-Ru")); if (currency == CurrencyCodes.EUR) { res = amountInUsd.ToString("F2", new CultureInfo("ru-Ru")) + "$ по курсу " + (1 / rate).ToString("F3", new CultureInfo("ru-Ru")); } return(res); }
public static EuroCurrencyConverter Create(string pricingDocumentCurrency) { // Currency CurrencyCodes iso4217CurrencyCode = DEFAULT_CODE; // default if (string.IsNullOrEmpty(pricingDocumentCurrency)) { iso4217CurrencyCode = DEFAULT_CODE; } else { try { iso4217CurrencyCode = (CurrencyCodes)Enum.Parse(typeof(CurrencyCodes), pricingDocumentCurrency); } catch (ArgumentException) { throw new NotSupportedException(string.Format("Currency code {0} in payload not supported or not ISO 4217 conform. Please choose one of following codes: {0}.", CurrencyConverterFactory.SupportedCurrencyCodes.ToString())); } } return(new EuroCurrencyConverter(iso4217CurrencyCode)); }
/// <summary> /// /// </summary> /// <param name="reader"></param> /// <param name="version"></param> /// <returns></returns> protected override bool TryParseElement(XmlReader reader, string version) { if (reader.IsReadingElementOf(OpdsNamespaces.Opds.Value, "price")) { var price = new OpdsPrice(); if (reader.HasAttributes) { if (reader.MoveToAttribute("currencycode")) { if (reader.ReadAttributeValue()) { price.CurrencyCode = reader.Value; if (!CurrencyCodes.IsValid(price.CurrencyCode)) { // TODO: Show Warning. } } reader.MoveToElement(); } } price.Price = reader.ReadElementContentAsDecimal(); prices.Add(price); } else if (reader.IsReadingElementOf(OpdsNamespaces.Opds.Value, "indirectAcquisition")) { ReadIndirectAcquisitions(reader, IndirectAcquisitions); } else { return(base.TryParseElement(reader, version)); } return(true); }
string GetUsdEquivalentString(decimal amount, CurrencyCodes currency, DateTime timestamp) { decimal temp; return(GetUsdEquivalentString(amount, currency, timestamp, out temp)); }
} // !Load() public static InvoiceDescriptor CreateInvoice(string invoiceNo, DateTime invoiceDate, CurrencyCodes currency, string invoiceNoAsReference = "") { InvoiceDescriptor retval = new InvoiceDescriptor { InvoiceDate = invoiceDate, InvoiceNo = invoiceNo, Currency = currency, InvoiceNoAsReference = invoiceNoAsReference }; return(retval); } // !CreateInvoice()
public double GetRate(CurrencyCodes fromCode, CurrencyCodes toCode, DateTime asOn) { // Don't use reflection if you want performance! return GetRate(Enum.GetName(typeof(CurrencyCodes), fromCode), Enum.GetName(typeof(CurrencyCodes), toCode), asOn); }
public virtual void DoExport(string catalogId, string[] exportedCategories, string[] exportedProducts, string pricelistId, string fulfilmentCenterId, CurrencyCodes currency, string languageCode, ExportNotification notification) { var memoryStream = new MemoryStream(); var streamWriter = new StreamWriter(memoryStream); streamWriter.AutoFlush = true; var productPropertyInfos = typeof(CatalogProduct).GetProperties(BindingFlags.Instance | BindingFlags.Public); string catalogName = null; using (var csvWriter = new CsvWriter(streamWriter)) { csvWriter.Configuration.Delimiter = ";"; //Notification notification.Description = "loading products..."; _notifier.Upsert(notification); try { //Load all products to export var products = LoadProducts(catalogId, exportedCategories, exportedProducts); //Notification notification.Description = "loading prices..."; _notifier.Upsert(notification); var allProductIds = products.Select(x=>x.Id).ToArray(); //Load prices for products var priceEvalContext = new PriceEvaluationContext { ProductIds = allProductIds, PricelistIds = pricelistId == null ? null : new string[] { pricelistId }, Currency = currency }; var allProductPrices = _pricingService.EvaluateProductPrices(priceEvalContext).ToArray(); foreach(var product in products) { product.Prices = allProductPrices.Where(x => x.ProductId == product.Id).ToList(); } //Load inventories notification.Description = "loading inventory information..."; _notifier.Upsert(notification); var allProductInventories = _inventoryService.GetProductsInventoryInfos(allProductIds); foreach (var product in products) { product.Inventories = allProductInventories.Where(x => x.ProductId == product.Id) .Where(x => fulfilmentCenterId == null ? true : x.FulfillmentCenterId == fulfilmentCenterId).ToList(); } notification.TotalCount = products.Count(); //populate export configuration Dictionary<string, Func<CatalogProduct, string>> exportConfiguration = new Dictionary<string, Func<CatalogProduct, string>>(); PopulateProductExportConfiguration(exportConfiguration, products); //Write header foreach (var cfgItem in exportConfiguration) { csvWriter.WriteField(cfgItem.Key); } csvWriter.NextRecord(); var notifyProductSizeLimit = 50; var counter = 0; //Write products foreach (var product in products) { if(catalogName == null && product.Catalog != null) { catalogName = product.Catalog.Name; } try { foreach (var cfgItem in exportConfiguration) { var fieldValue = String.Empty; if (cfgItem.Value == null) { var propertyInfo = productPropertyInfos.FirstOrDefault(x => x.Name == cfgItem.Key); if (propertyInfo != null) { var objValue = propertyInfo.GetValue(product); fieldValue = objValue != null ? objValue.ToString() : fieldValue; } } else { fieldValue = cfgItem.Value(product); } csvWriter.WriteField(fieldValue); } csvWriter.NextRecord(); } catch(Exception ex) { notification.ErrorCount++; notification.Errors.Add(ex.ToString()); _notifier.Upsert(notification); } //Raise notification each notifyProductSizeLimit products counter++; notification.ProcessedCount = counter; notification.Description = string.Format("{0} of {1} products processed", notification.ProcessedCount, notification.TotalCount); if (counter % notifyProductSizeLimit == 0) { _notifier.Upsert(notification); } } memoryStream.Position = 0; //Upload result csv to blob storage var uploadInfo = new UploadStreamInfo { FileName = "Catalog-" + (catalogName ?? catalogId) + "-export.csv", FileByteStream = memoryStream, FolderName = "temp" }; var blobKey = _blobStorageProvider.Upload(uploadInfo); //Get a download url notification.DownloadUrl = _blobUrlResolver.GetAbsoluteUrl(blobKey); notification.Description = "Export finished"; } catch(Exception ex) { notification.Description = "Export error"; notification.ErrorCount++; notification.Errors.Add(ex.ToString()); } finally { notification.Finished = DateTime.UtcNow; _notifier.Upsert(notification); } } }
public static Currency Get(CurrencyCodes currencyCode) { return Exists(currencyCode) ? CurrencyDictionary[currencyCode] : null; }
private static string GetDefaultPriceListName(CurrencyCodes currency) { var retVal = "Default" + currency.ToString(); return retVal; }
public EuroCurrencyConverter(CurrencyCodes targetCurrencyCode) { this.Initialize(targetCurrencyCode); }
public static bool Exists(CurrencyCodes currencyCode) { return CurrencyDictionary.ContainsKey(currencyCode); }
public ZugferdInvoice(string invoiceNumber, DateTime invoiceDate, CurrencyCodes currency) { InvoiceNumber = invoiceNumber; InvoiceDate = invoiceDate; Currency = currency; }