Category: async

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:

  1. How we can display the errors ?
  2. What if the data exists already for this day and I cannot save into database, because it exists ?
  3. How to acknowledge what exists and what not , in one operation ?
  4. How to report success even if data exists ? Should we report number of records?
  5.  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/ )
NrPost 
1Start
2Reading NBR from internet
3Source control and build
4Badge and test
5CI and action
6Artifacts and dotnet try
7Docker with .NET Try
8ECB
9Intermezzo - Various implementations for programmers
10Intermezzo - similar code - options
11Plugin implementation
12GUI for console
13WebAPI
14Plugin in .NET Core 3
15Build and Versioning
16Add swagger
17Docker - first part
18Docker - second part
19Docker - build Azure
20Pipeline send to Docker Hub
21Play with Docker - online
22Run VSCode and Docker
23Deploy Azure
24VSCode see tests and powershell
25Code Coverage
26Database in Azure
27Sql In Memory or Azure
28Azure ConString, RSS
29Middleware for backward compatibility
30Identical Tables in EFCore
31Multiple Data in EFCore
32Dot net try again
33Start Azure Function
34Azure function - deploy
35Solving my problems
36IAsyncEnumerable transformed to IEnumerable and making Azure Functions works
37Azure functions - final
38Review of 37 hours
39Last Commit in AzureDevOps
40Create Angular WebSite
41Add static Angular to WebAPI .NET Core
42Docker for Angular
43Angular and CORS
44SSL , VSCode, Docker
45Routing in Angular
46RxJS for Routing
47RxJs Unsubscribe

My Async Await tutorials

Rule of thumb: just await / async from top to down.

 

To deeply understand async await in .NET Core , please follow the following resources:

 

1. https://channel9.msdn.com/Events/TechDays/Techdays-2014-the-Netherlands/Async-programming-deep-dive  – to gain inner knowledge about what code is async / await

2. Read https://blog.stephencleary.com/2012/02/async-and-await.html to have started into async await

3. Read MSDN for a better understanding : https://msdn.microsoft.com/en-us/magazine/jj991977.aspx?f=255&MSPPError=-2147217396

4. Common pitfalls in ASP.NET  Framework( not in console! ) with async await: https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html

5. No problem in ASP.NET Core: https://blog.stephencleary.com/2017/03/aspnetcore-synchronization-context.html

Happy reading !

Asynchronous code and exceptions

There are 2 kinds of coding when handling asynchronous code.

The first one is  calling Result:

<

The second is async /await

public async Task<bool> TwoTask() {

//code

await Task.WhenAll(file, console);
return file.Result & console.Result;

}

As such, we will have 2 intercepting code.

For the first one we will catch AggregateException

try
            {
                Console.WriteLine(t.TwoTask().Result);
            }
            catch (AggregateException ex)
            {
                Console.WriteLine("Aggregate number of exceptions :"+ex.InnerExceptions.Count);
            }

For the second one we will catch the FIRST task  exception  ( or , more generic , Exception ) – and see what other tasks have been doing

try

try
            {
                await Task.WhenAll(file, console);
                return file.Result & console.Result;
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine("Exception is " + ex.Message);
                
                if (file.IsFaulted)
                {
                    Console.WriteLine("file is faulted exceptions :" + file.Exception.InnerExceptions.Count);
                    
                }
                if (console.IsFaulted)
                {
                    Console.WriteLine("console is faulted exceptions :" + console.Exception.InnerExceptions.Count);
                }
                
                throw;
            }

Maybe it is better when you see a video demo: Async await and exceptions at https://youtu.be/1a9s74IfSE8

Andrei Ignat weekly software news(mostly .NET)

* indicates required

Please select all the ways you would like to hear from me:

You can unsubscribe at any time by clicking the link in the footer of our emails. For information about our privacy practices, please visit our website.

We use Mailchimp as our marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp's privacy practices here.