static void Main(string[] args) { try { Currency balance = new Currency(50,35); Console.WriteLine(balance); Console.WriteLine("balance is " + balance); Console.WriteLine("balance is (using ToString()) " + balance.ToString()); float balance2 = balance; Console.WriteLine("After converting to float, = " + balance2); balance = (Currency)balance2; Console.WriteLine("After converting back to Currency, = " + balance); Console.WriteLine("Now attempt to convert out of range value of " + "-$50.50 to a Currency:"); checked { balance = (Currency)(-50.50); Console.WriteLine("Result is " + balance.ToString()); } } catch (Exception e) { Console.WriteLine("Exception occurred: " + e.Message); } Console.ReadLine(); }
private static List<Transaction> GetTransactionsList(string fileName, Currency currency, string price, string quantity, string fileId, string userId) { var transactionList = new List<Transaction>(); transactionList.Add(new Transaction() { invoice_number = fileId + "_" + userId, amount = new Amount() { currency = currency.ToString().ToUpper(), total = price, // Total must be equal to sum of shipping, tax and subtotal. }, item_list = new ItemList() { items = new List<Item>() { new Item() { name = fileName, currency = currency.ToString().ToUpper(), price = price, quantity = quantity, sku = fileId } } } }); return transactionList; }
public CurrencyInfo GetCurrencyInfo(Currency currency) { CurrencyInfoResponse currencyInfoResponse = restClient.GetResponse<CurrencyInfoResponse>(String.Format("BTC{0}/money/currency", currency.ToString()), Method.POST, null, AccessType.Public); if(currencyInfoResponse.CurrencyInfo == null) throw new Exception("Failed to deserialize JSON object of type " + typeof(CurrencyInfo) + ". " + MtGoxRestClient.lastResponse); return currencyInfoResponse.CurrencyInfo; }
public Depth GetDepth(Currency currency) { DepthResponse depthResponse = restClient.GetResponse<DepthResponse>(String.Format("BTC{0}/money/depth/fetch", currency.ToString()), Method.GET, null, AccessType.Public); if (depthResponse.Depth == null) throw new Exception("Failed to deserialize JSON object of type " + typeof(Depth) + ". " + MtGoxRestClient.lastResponse); return depthResponse.Depth; }
/// <summary> /// 0/buyBTC.php /// </summary> public List<Order> buyBTC(double amount, Currency currency, double price = 0.0) { try { string url = (this.baseURL) + "0/buyBTC.php"; string postData; if (price == 0.0) postData = "amount=" + amount + "¤cy=" + currency.ToString(); else postData = "amount=" + amount + "&price=" + price + "¤cy=" + currency.ToString(); string responseStr = DoAuthenticatedAPIPost(url, apiKey, apiSecret, postData); var resp = JSON.Instance.ToObject<OrderResponse>(responseStr); return resp.orders; } catch (Exception ex) { return null; } }
public OrderCreateResponse CreateOrder(Currency currency, OrderType type, double amount, double? price) { NameValueCollection nvc = new NameValueCollection { {"type", type.ToString().ToLower()}, {"amount_int", (Math.Round(amount, 8)*100000000).ToString()} }; if(price != null) nvc.Add("price_int", (Math.Round((double)price,5)*100000).ToString()); return restClient.GetResponse<OrderCreateResponse>(String.Format("BTC{0}/money/order/add", currency.ToString()), Method.POST, nvc, AccessType.Private); }
protected void LicenseBound(Object sender, RepeaterItemEventArgs e) { var cartProvider = (ICartProvider)MarketplaceProviderManager.Providers["CartProvider"]; ICart _cart = cartProvider.GetCurrentCart(); _currency = _cart.Currency; Literal _name = (Literal)e.Item.FindControl("LicenseType"); Literal _price = (Literal)e.Item.FindControl("LicensePrice"); ImageButton _addToCart = (ImageButton)e.Item.FindControl("LicenseAddToCart"); var License = (ILicense)e.Item.DataItem; switch (License.LicenseType) { case LicenseType.Domain: _name.Text = "Domain"; break; case LicenseType.IP: _name.Text = "IP"; break; case LicenseType.Unlimited: _name.Text = "Unlimited"; break; case LicenseType.SourceCode: _name.Text = "Source Code"; break; default: break; } _price.Text = DeliCurrency.FriendlyConvertFromEuro((decimal)License.Price, DeliCurrency.FromSymbol(_currency.ToString())); _addToCart.CommandArgument = License.Id.ToString(); if (!String.IsNullOrEmpty(Project.GACode)) { var eventCategory = "_" + Project.Name.ToLower().Replace(" ", ""); _addToCart.OnClientClick = "vendorTracker._trackEvent('" + eventCategory + "', 'Add To Cart - " + _name.Text + "', '" + Project.Name + " " + _name.Text + "'," + License.Price + ");"; } }
public static decimal ToAUD(decimal price, Currency sourceCurrency, Currency destinationCurrency) { try { var client = new WebClient(); var response = client.DownloadString(string.Format("http://www.google.com/ig/calculator?hl=en&q={0}{1}=?{2}", price, sourceCurrency.ToString(), destinationCurrency.ToString())); string value = response.Substring(response.IndexOf("rhs")); value = value.Substring(0, value.IndexOf(",")); string decimalValue = ""; foreach (char c in value) { if (char.IsDigit(c) || c == '.') decimalValue += c; } return Math.Round(Convert.ToDecimal(decimalValue), 2); } catch { return 0; } }
public static int InsertBondLimit(int? counterpartyID, int? counterpartyGroupID, double limitValue, Currency cur, bool considerRevRepo, DateTime startDate) { if (counterpartyID == null && counterpartyGroupID == null) throw new ArgumentException("counterpartyID == null && counterpartyGroupID == null"); if (counterpartyID != null && counterpartyGroupID != null) throw new ArgumentException("counterpartyID != null && counterpartyGroupID != null"); if (limitValue <= 0) throw new ArgumentException("limitValue <= 0"); string script = @" declare @limitID int; set @limitID = (select max(ID)+1 from t_Cpty_Limit); declare @fullName nvarchar(300); declare @shortName nvarchar(300); if (@cptyID is not null) select @fullName = Client_Name, @shortName = Client_ShortName from t_Client where ID = @cptyID; else select @fullName = NameCptyGroup, @shortName = SNameCptyGroup from t_CptyGroup where ID = @cptyGroupID; insert into t_Cpty_Limit(ID, MasterLimitType, Limit_Type, Limit_Value, Limit_Currency, Limit_Unit, Limit_Date_Start, InstrumentType_ID, Cpty_ID, CtptyGroup_ID, Cpty_ShortName, Cpty_Name, PortfolioGroup_ID) values(@limitID, 'counterparty', 'credit', @limitValue, @limitCurrency, 'currency', @startDate, @instrumentType_ID, @cptyID, @cptyGroupID, @shortName, @fullName, null)"; SqlCommand cmd = DBHelper.CreateCommand(RiskSettings.ConnStr, script, DBHelper.CreateParameter("@limitValue", limitValue), DBHelper.CreateParameter("@limitCurrency", cur.ToString().ToUpper()), DBHelper.CreateParameter("@startDate", startDate), DBHelper.CreateParameter("@instrumentType_ID", considerRevRepo ? -1 : (int?)null), DBHelper.CreateParameter("@cptyID", counterpartyID), DBHelper.CreateParameter("@cptyGroupID", counterpartyGroupID)); DBHelper.ExecuteNonQuery(cmd); return 0; }
/// <summary> /// 0/data/getDepth.php /// </summary> public Depth getDepth(Currency currency) { try { string url = (this.baseURL) + "0/data/getDepth.php?currency=" + currency.ToString(); string postData = ""; string responseStr = DoAuthenticatedAPIPost(url, apiKey, apiSecret, postData); Depth returnValue = new Depth();//Depth.getObjects(responseStr); return returnValue; } catch (Exception ex) { return null; } }
public static string GetFutureSearchCriteria(string description = "", string root = "", FutureType futureType = FutureType.Electronic, Currency currency = Currency.USD, bool includeExpired = false, CountryCode country = CountryCode.ALL) { StringBuilder criteria = new StringBuilder(255); Append(criteria, "c=" + SearchCategory.Future.ToString()); if (description != string.Empty) Append(criteria, "desc=" + description); if (root != string.Empty) Append(criteria, "r=" + root); if (futureType != FutureType.Electronic) Append(criteria, "FT=" + futureType.ToString()); if (currency != Currency.USD) Append(criteria, "Cur=" + currency.ToString()); if (includeExpired) Append(criteria, "Exp=true"); if (country != CountryCode.ALL) Append(criteria, "Cnt=" + country.ToString()); return criteria.ToString(); }
public void AddCell(Currency text) { AddCell(text.ToString()); }
public TradeResponse GetTrades(Currency currency, DateTime? fromDateTime) { TradeResponse tradeResponse; if (fromDateTime.HasValue) { DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); TimeSpan span = ((DateTime)fromDateTime - epoch); Int64 since = (Int64)Decimal.Round(Decimal.Divide(span.Ticks, 10), 0); tradeResponse = restClient.GetResponse<TradeResponse>(String.Format("BTC{0}/money/trades/fetch?since={1}", currency.ToString(), since), Method.GET, null, AccessType.Public); } else { tradeResponse = restClient.GetResponse<TradeResponse>(String.Format("BTC{0}/money/trades/fetch", currency.ToString()), Method.GET, null, AccessType.Public); } if (tradeResponse.Trades == null) throw new Exception("Failed to deserialize JSON object of type " + typeof(List<Trade>) + ". " + MtGoxRestClient.lastResponse); return tradeResponse; }
public Ticker GetTicker(Currency currency) { MtGoxTickerResponse tickerResponse = restClient.GetResponse<MtGoxTickerResponse>(String.Format("BTC{0}/money/ticker", currency.ToString()), Method.GET, null, AccessType.Public); if (tickerResponse.Ticker == null) throw new Exception("Failed to deserialize JSON object of type " + typeof(MtGoxTicker) + ". " + MtGoxRestClient.lastResponse); return new Ticker(tickerResponse.Ticker); }
public void ToStringTest() { Symbols sym = Symbols.USD; Decimal amount = 2.2M; Currency target = new Currency(sym, amount); string expected = "USD 2.20"; string actual; actual = target.ToString(); Assert.AreEqual(expected, actual); }
/// <summary> /// 0/history_[CUR].csv /// </summary> public string history_CUR(Currency currency) { try { string url = (this.baseURL) + "0/history_" + currency.ToString() + ".csv"; string postData = ""; string responseStr = DoAuthenticatedAPIPost(url, apiKey, apiSecret, postData); return responseStr; } catch (Exception ex) { return null; } }
static void Main(string[] args) { Console.WindowHeight = 60; var ci = new CultureInfo("en-NZ"); var mfi = new MeasurementFormatInfo(ci.NumberFormat); var dict = new HybridDictionary(); dict["FuelEfficiency"] = "km/L;0.0"; dict["Length"] = "in"; dict["MassFlow"] = "t/d;0.00000"; dict["Angle"] = ">+0d0'0.00\""; dict["Angle~brg"] = "<{>B} ({>+000d})"; dict["Angle~test"] = "<{~brg} {/3.1415926536;0.00}\u03C0 {!;0.0} {*} {%} {>x}"; mfi.SetPreferences(dict); var ang1 = Angle.Degrees(-25); string sAng1 = ang1.ToString("~test", mfi); Console.WriteLine("composite format: 25deg: {0}", sAng1); var ang2 = Angle.Degrees(333); string sAng2 = ang2.ToString("~brg", mfi); Console.WriteLine("composite format: 333deg: {0} {1:>X}", sAng2, ang2); for (int deg3 = 0; deg3 < 700; deg3 += 50) { Angle ang3 = Angle.Degrees(deg3); string sAng3 = ang3.ToString("<{!},{>0d},{>+0d},{>-000d00'00.0\"}", mfi); Console.WriteLine("normal, full and half: {0}", sAng3); } string x1 = string.Format(mfi, "\r\nUnitless: {0:*}" + // unitless SI value "\r\nKnown unit: {1:km/L}" + // use km/L unit "\r\nMultiplier: {2:*3.6;0,000.000}" + // unitless, multiply SI value "\r\nCanonical: {3:!;0.00}" + // show simple SI base units with dots between units "\r\nSI base: {4:^}" + // show simple SI base units without dots between, and using superscripts for 1..3 "\r\nAngle: {5:deg;0.0}" + // display unit different from the lookup key "\r\nCurrency: {6:@}" + // @ is the lookup character for the generic currency symbol "\r\nTemperature: {7:degF;0.0}" + // temperature scale conversion "\r\nFeet: {8:';30.0}" + // use of ' mark "\r\nPreferred: {9}" + // uses the preferences in MeasureFormatInfo "\r\nEasy unit: {10: m3}" + // converts 3 to superscript before lookup "\r\nSlash unit: {11:ps;0}" // 'per' ... , Length.Metre(10) //0 , FuelEfficiency.KmPerLitre(11.5) //1 , Speed.MetrePerSec(893483.0) //2 , Pressure.Pascal(1013.293840129348) //3 , Volume.CubicMetre(7.0012) //4 , Angle.Degrees(89.55) //5 , new Currency(1200) //6 , Temperature.Kelvin(233.15) //7 , Length.Metre(3) //8 , MassFlow.KgPerSec(2.3) // 9 , Volume.USGallon(100.0) // 10 , Frequency.Hertz(60) // 11 ); var m1 = new Measurement(0.1334, new MUnit(2, 3, -1, 0, 0, 1, 0)); string x2 = string.Format(mfi, "\r\nCanonical {0:!}" + "\r\nSuperscript {1:^}" + "\r\nUnitless {2:*}" + "\r\nMultiplier {3:*100}%" + "\r\nDivider {4:/2}" + "\r\nPreferred {5}" , m1, m1, m1, m1, m1, m1 ); Console.WriteLine(x1); Console.WriteLine(x2); Console.WriteLine(FuelEfficiency.USGallonPer100Mile(5.0).ToString(null, mfi)); string q; Console.WriteLine(Angle.Degrees(-123.457).ToString(">000E 00' 00.0\"", mfi)); Console.WriteLine(q = Angle.Degrees(-123.457).ToString(">#DN 00' 00.0\"", mfi)); Console.WriteLine(Angle.Degrees(3.457).ToString(">000.00000d", mfi)); Console.WriteLine(Angle.Degrees(-6.1234123).ToString(">0.00000d 0.00000' 0.00000\u2033", mfi)); Console.WriteLine("---"); var time = Time.Hours(2); var speed = Speed.Kph(20); var length = (Length)((Measurement)speed * time); Console.WriteLine(string.Format(mfi, "Length = {0:km}", length)); Console.WriteLine(Length.Metre(20).ToString("yd", mfi)); Console.WriteLine(string.Format(mfi, "-> {0}", Length.Metre(0.01))); Console.WriteLine("=> " + Length.Metre(0.01).ToString(null, mfi)); //string s = FuelEfficiency.KmPerLitre(14.5).ToString("gal/100mi", measureFormatInfo); string s = Angle.Degrees(45).ToString("%;0.0", mfi); Console.WriteLine(s); var a = Length.Metre(5e-9); var ss = string.Format(mfi, "{0:/1e-9;0}nm = {1:*1e9;0}nm", a, a); Console.WriteLine(ss); ss = string.Format(mfi, "{0:*;0}nm", new Measurement(a.InSI(SIPrefix.Nano))); Console.WriteLine(ss); var fe1 = FuelEfficiency.KmPerLitre(11).ToString("<{km/L;0.0} ({L/100km;0})", mfi); Console.WriteLine("FE: " + fe1); var sp1 = Speed.Kph(5.1).ToString("<{*86.4;0}km/24h", mfi); Console.WriteLine("Daily distance " + sp1); string z = "Length:12"; Length l1 = (Length)Measurement.Parse(z); Length l2 = Measurement.Parse<Length>(z); Console.WriteLine("{0}", l1); Console.WriteLine(l2); FuelEfficiency ff = FuelEfficiency.KmPerLitre(11); z = Measurement.PString(ff); Console.WriteLine(z); FuelEfficiency ff2 = Measurement.Parse<FuelEfficiency>(z); Console.WriteLine(string.Format(mfi, "FuelEfficiency, Preferred: {0}", ff2)); Console.WriteLine(ff2.ToString(null, mfi)); if ((Measurement)ff2 != ff) Console.WriteLine("not the same"); var m2 = new Measurement(17.7, new MUnit(-1, -1, -3, 0, 1, -1, 2)); Console.WriteLine(m2.ToString(null, mfi)); z = Measurement.PString(m2); Console.WriteLine(z); var m3 = Measurement.Parse(z); Console.WriteLine(m3); var forex = mfi.ExchangeRates; forex["USD"] = 1.0; forex["NZD"] = 1.3839; forex["EUR"] = 0.6870; forex["DKK"] = 5.1121; var c1 = new Currency(34.98); var cs1 = c1.ToString("<{>USD;0 @} {>NZD;c} {>EUR;\u20AC0.00} {>DKK } {>XYZ;0} {@} {$}", mfi); Console.WriteLine("Currency: " + cs1); Console.WriteLine(new Currency(12000).ToString(">NZD ;@0;@(0);nil", mfi)); var c2 = new Currency(36.00, "NZD", mfi); var cs2 = c2.ToString("<{>NZD;c} stored as {*}", mfi); Console.WriteLine("Conversion: "+ cs2); string[] af = { Measurement.Format("Angle:2", null), Measurement.Format("Angle:2", mfi), Measurement.Format("Angle:2 ~brg", mfi), Measurement.Format("Angle:2 ~test", mfi), Measurement.Format("Angle:2 !;0.0", mfi), Measurement.Format("Angle:2 <quadrant {>X} {>b}", mfi), Measurement.Format("Angle:2 deg", mfi), Measurement.Format("Currency:750 >NZD;c", mfi), Measurement.Format("M:123;1,1,1,-1,-2,-2,1 <{!} ({*;0} units)", mfi), }; Console.WriteLine("Measurement.Format()"); foreach (string afi in af) Console.WriteLine(" {0}", afi); Console.ReadKey(); }
/// <summary> /// Операция для получения токена /// </summary> /// <param name="amount">Стоимость</param> /// <param name="currencyCode">Валюта</param> /// <param name="action">Действие на сайте PayPal, которое пользователь должен будет сделать</param> /// <param name="cancelUrl">URL, куда перенаправят пользователя в случае ошибки или отказа от проведения платежа</param> /// <param name="returnUrl">URL, куда перенаправят пользователя в случае успешного выполнения платежа</param> /// <returns>Все параметры, которые пришли от PayPal</returns> public Dictionary<string, string> GetToken(Currency currencyCode, PayAction action, string cancelUrl, string returnUrl) { var errList = Validate(); if (errList.Count != 0) { throw new Exception("Can`t get PayPal token because an error has occurred: " + string.Join(",", errList.ToArray())); } if (string.IsNullOrWhiteSpace(cancelUrl)) { throw new Exception("Cancel url is not defined"); } if (string.IsNullOrWhiteSpace(returnUrl)) { throw new Exception("Successfull url is not defined"); } var retDict = new Dictionary<string, string>(); /* --- Получаем сумму для оплаты --- */ decimal amount = basket.Sum(t => Convert.ToDecimal(t.Amount)); /* --- !Получаем сумму для оплаты --- */ var client = new WebClient(); var requestStr = new StringBuilder(); requestStr.Append(string.Format("{0}/?USER={1}&PWD={2}&SIGNATURE={3}&METHOD=SetExpressCheckout&VERSION={4}&PAYMENTREQUEST_0_AMT={5}&PAYMENTREQUEST_0_CURRENCYCODE={6}&PAYMENTREQUEST_0_PAYMENTACTION={7}&cancelUrl={8}&returnUrl={9}", PayPalURL, User, Password, Signature, Version, amount.ToString("F").Replace(',','.'), currencyCode.ToString("F"), action.ToString("F"), cancelUrl, returnUrl)); requestStr.Append(currencyCode == Currency.RUB ? "&LOCALECODE=RU" : "&LOCALECODE=US"); for (int i = 0; i < basket.Count; i++) { requestStr.Append(string.Format("&L_PAYMENTREQUEST_0_NAME{0}={1}&L_PAYMENTREQUEST_0_DESC{0}={2}&L_PAYMENTREQUEST_0_AMT{0}={3}&L_PAYMENTREQUEST_0_QTY{0}={4}", i, basket[i].Name, basket[i].Description, basket[i].Amount.Replace(',', '.'), basket[i].Quantity)); } var sr = new StreamReader(client.OpenRead(requestStr.ToString())); string newLine; while ((newLine = sr.ReadLine()) != null) { foreach (var curPair in newLine.Split('&')) { var pairKeyVal = curPair.Split('='); retDict.Add(pairKeyVal[0], pairKeyVal[1]); } } TokenResponse = retDict; return retDict; }
public string BuildFileName(DataItem dataItem, Resolution resolution, Currency currencye) { var url = "{0}_{1}_{2}"; url = string.Format(url, dataItem.ToXString(), resolution.ToXString(), currencye.ToString()); return url; }