Neuron®
The Neuron® is the basis for the creation of open and secure federated networks for smart societies.
Loading...
Searching...
No Matches
OpenExchangeRateClient.cs
1using System;
2using System.Collections.Generic;
3using System.Text;
4using System.Threading.Tasks;
5using System.Web;
6using Waher.Content;
8using Waher.Script;
9
11{
13 {
14 private readonly string apiKey;
15
21 {
22 this.apiKey = ApiKey;
23 }
24
28 public string ApiKey => this.apiKey;
29
30
31 #region HTTP Layer
32
33 private async Task<T> RequestRespond<T>(string Url, string ResponseElement,
34 params KeyValuePair<string, string>[] Parameters)
35 {
36 StringBuilder sb = new StringBuilder();
37
38 sb.Append("https://openexchangerates.org/api/");
39 sb.Append(Url);
40 sb.Append("?app_id=");
41 sb.Append(this.apiKey);
42
43 foreach (KeyValuePair<string, string> P in Parameters)
44 {
45 sb.Append('&');
46 sb.Append(HttpUtility.UrlEncode(P.Key));
47 sb.Append('=');
48 sb.Append(HttpUtility.UrlEncode(P.Value));
49 }
50
51 Uri Uri = new Uri(sb.ToString());
52
53 if (!(await InternetContent.GetAsync(Uri, new KeyValuePair<string, string>[]
54 {
55 new KeyValuePair<string, string>("Accept", "application/json"),
56 }) is Dictionary<string, object> Result))
57 {
58 throw new Exception("Unexpected response returned from openexchangerates.org.");
59 }
60
61 if (string.IsNullOrEmpty(ResponseElement))
62 {
63 if (Result is T Response)
64 return Response;
65 }
66 else if (Result.TryGetValue(ResponseElement, out object Obj))
67 {
68 if (Obj is T Response2)
69 return Response2;
70 else if (System.Convert.ChangeType(Obj, typeof(T)) is T Response3)
71 return Response3;
72 }
73
74 throw new Exception("Unexpected response returned from openexchangerates.org.");
75 }
76
77 #endregion
78
79 #region Get Latest
80
85 public Task<ExchangeRate[]> GetLatest()
86 {
87 return this.GetLatest(null, null, false);
88 }
89
95 public Task<ExchangeRate[]> GetLatest(string BaseCurrency)
96 {
97 return this.GetLatest(BaseCurrency, null, false);
98 }
99
105 public Task<ExchangeRate[]> GetLatest(string[] Symbols)
106 {
107 return this.GetLatest(null, Symbols, false);
108 }
109
115 public Task<ExchangeRate[]> GetLatest(bool ShowAlternative)
116 {
117 return this.GetLatest(null, null, ShowAlternative);
118 }
119
126 public Task<ExchangeRate[]> GetLatest(string BaseCurrency, string[] Symbols)
127 {
128 return this.GetLatest(BaseCurrency, Symbols, false);
129 }
130
137 public Task<ExchangeRate[]> GetLatest(string BaseCurrency, bool ShowAlternative)
138 {
139 return this.GetLatest(BaseCurrency, null, ShowAlternative);
140 }
141
149 public async Task<ExchangeRate[]> GetLatest(string BaseCurrency, string[] Symbols,
150 bool ShowAlternative)
151 {
152 List<KeyValuePair<string, string>> Request = new List<KeyValuePair<string, string>>()
153 {
154 new KeyValuePair<string, string>("show_alternative", CommonTypes.Encode(ShowAlternative))
155 };
156
157 if (!string.IsNullOrEmpty(BaseCurrency))
158 Request.Add(new KeyValuePair<string, string>("base", BaseCurrency));
159
160 if (!(Symbols is null) && Symbols.Length > 0)
161 {
162 StringBuilder sb = new StringBuilder();
163 bool First = true;
164
165 foreach (string Symbol in Symbols)
166 {
167 if (First)
168 First = false;
169 else
170 sb.Append(',');
171
172 sb.Append(Symbol);
173 }
174
175 Request.Add(new KeyValuePair<string, string>("symbols", sb.ToString()));
176 }
177
178 Dictionary<string, object> Response = await this.RequestRespond<Dictionary<string, object>>("latest.json", null,
179 Request.ToArray());
180
181 if (Response.TryGetValue("base", out object Obj) && Obj is string Base &&
182 Response.TryGetValue("rates", out Obj) && Obj is Dictionary<string, object> Rates)
183 {
184 int i = 0, c = Rates.Count;
185 ExchangeRate[] Result = new ExchangeRate[c];
186 Dictionary<CaseInsensitiveString, decimal> Reference = new Dictionary<CaseInsensitiveString, decimal>();
187 DateTime TP = DateTime.UtcNow;
188
189 foreach (KeyValuePair<string, object> P in Rates)
190 {
191 decimal d = Expression.ToDecimal(P.Value);
192
193 Result[i++] = new ExchangeRate(Base, P.Key, d, TP, "openexchangerates.org");
194 Reference[P.Key] = d;
195 }
196
197 return Result;
198 }
199 else
200 throw new Exception("Unexpected response returned from openexchangerates.org.");
201 }
202
203 #endregion
204
205 #region Get Currencies
206
213 public Task<CurrencySymbol[]> GetCurrencies()
214 {
215 return this.GetCurrencies(false, false);
216 }
217
226 public async Task<CurrencySymbol[]> GetCurrencies(bool ShowAlternative, bool ShowInactive)
227 {
228 Dictionary<string, object> Symbols = await this.RequestRespond<Dictionary<string, object>>("currencies.json", null,
229 new KeyValuePair<string, string>("show_alternative", CommonTypes.Encode(ShowAlternative)),
230 new KeyValuePair<string, string>("show_inactive", CommonTypes.Encode(ShowInactive)));
231 int i = 0, c = Symbols.Count;
232 CurrencySymbol[] Result = new CurrencySymbol[c];
233
234 foreach (KeyValuePair<string, object> P in Symbols)
235 Result[i++] = new CurrencySymbol(P.Key, P.Value?.ToString());
236
237 return Result;
238 }
239
240 #endregion
241
242 #region Convert
243
248 public async Task<decimal> Convert(CaseInsensitiveString From, CaseInsensitiveString To, int Amount)
249 {
250 StringBuilder sb = new StringBuilder();
251
252 sb.Append("convert/");
253 sb.Append(Amount.ToString());
254 sb.Append('/');
255 sb.Append(From.Value.ToUpper());
256 sb.Append('/');
257 sb.Append(To.Value.ToUpper());
258
259 double Converted = await this.RequestRespond<double>(sb.ToString(), "result");
260
261 return (decimal)Converted;
262 }
263
264 #endregion
265
266 }
267}
Task< ExchangeRate[]> GetLatest(string[] Symbols)
Gets latest exchange rates.
OpenExchangeRateClient(string ApiKey)
Currency Converter service from openexchangerates.org.
Task< ExchangeRate[]> GetLatest(bool ShowAlternative)
Gets latest exchange rates.
Task< ExchangeRate[]> GetLatest(string BaseCurrency, bool ShowAlternative)
Gets latest exchange rates.
Task< ExchangeRate[]> GetLatest(string BaseCurrency, string[] Symbols)
Gets latest exchange rates.
async Task< ExchangeRate[]> GetLatest(string BaseCurrency, string[] Symbols, bool ShowAlternative)
Gets latest exchange rates.
Task< ExchangeRate[]> GetLatest(string BaseCurrency)
Gets latest exchange rates.
async Task< CurrencySymbol[]> GetCurrencies(bool ShowAlternative, bool ShowInactive)
Gets supported currency symbols.
async Task< decimal > Convert(CaseInsensitiveString From, CaseInsensitiveString To, int Amount)
Converts an amount from one currency to another.
Task< CurrencySymbol[]> GetCurrencies()
Gets supported currency symbols.
Task< ExchangeRate[]> GetLatest()
Gets latest exchange rates.
Helps with parsing of commong data types.
Definition: CommonTypes.cs:13
static string Encode(bool x)
Encodes a Boolean for use in XML and other formats.
Definition: CommonTypes.cs:594
Static class managing encoding and decoding of internet content.
static Task< object > GetAsync(Uri Uri, params KeyValuePair< string, string >[] Headers)
Gets a resource, given its URI.
Represents a case-insensitive string.
string Value
String-representation of the case-insensitive string. (Representation is case sensitive....
Class managing a script expression.
Definition: Expression.cs:39
static decimal ToDecimal(object Object)
Converts an object to a double value.
Definition: Expression.cs:4883