Saving multiple data–part 31
I want to load the exchange rates from NBR and ECB and load at once .From here, the challenges of programming for a simple task like this:
- How we can display the errors ?
- What if the data exists already for this day and I cannot save into database, because it exists ?
- How to acknowledge what exists and what not , in one operation ?
- How to report success even if data exists ? Should we report number of records?
- How we can perform async all that stuff and, however , report errors ?
If you know the answer to all that, I have a challenge for you: see the file at https://github.com/ignatandrei/InfoValutar/blob/master/InfoValutar/InfovalutarLoadAndSave/LoadAndSaveLastData.cs– and improve it.
Until then, I come with this simple code
public class ResultsLoadBankData { public string Bank { get; internal set; } public int NrRecords { get; internal set; } public bool HasSuccess { get; internal set; } public string ErrorMessage { get; internal set; } } //in some class below public async Task<ResultsLoadBankData[]> LoadAndSave() { var items= providers.Banks().Select(it => new KeyValuePair<string, ResultsLoadBankData>(it, new ResultsLoadBankData() { Bank = it, ErrorMessage=null, HasSuccess=true, NrRecords=0 }) ); var lst = new Dictionary<string, ResultsLoadBankData>(items); var rates = providers.LoadExchange() .Select(it => it.GetActualRates()) .ToArray(); //TODO: how to load async all async enumerables? //TODO: how to report error if one fails? foreach (var rateAsync in rates) { await foreach(var rate in rateAsync) { var item = lst[rate.Bank]; try { if (await ret.Exists(rate)) continue; var nr = await save.Save(rate); item.NrRecords++; } catch(Exception ex) { //TODO:log item.ErrorMessage = ex.Message; item.HasSuccess = false; } } } return lst.Values.ToArray(); }
Infovalutar
And one hour passes...(This is the result of 1 hour per day auto-challenge as a full cycle developer for an exchange rates application)
( You can see the sources at https://github.com/ignatandrei/InfoValutar/ )
Leave a Reply