Beispiel #1
0
        public async Task <IActionResult> Upload()
        {
            IFormFile file = Request.Form.Files.First();

            if (file != null)
            {
                //Only one file
                var path = Path.Combine(hostingEnvironment.WebRootPath, file.FileName);
                using (var stream = new FileStream(path, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }

                var header = new CalculationHeader {
                    FileName = file.FileName, Status = "Pending", Size = (int)file.Length, UploadTime = DateTime.Now
                };
                await context.CalculationHeaders.AddAsync(header);

                await context.SaveChangesAsync();

                await messageSession.SendLocal(new CalculationCommand { Filename = path, HeaderId = header.Id });

                return(Accepted());
            }
            return(BadRequest("No file uploaded"));
        }
        public async Task Handle(CalculationCommand message, IMessageHandlerContext context)
        {
            var result = new List <Calculation>();
            var errors = new List <CalculationResult> {
            };

            parser.Read(message.Filename).AsParallel().ForAll(line =>
            {
                try
                {
                    result.Add(parser.ProcessLine(line));
                }

                catch (Exception ex)
                {
                    errors.Add(new CalculationResult()
                    {
                        Message             = ex.Message,
                        CalculationHeaderId = message.HeaderId,
                        Formular            = line.Split(';')[0]
                    });
                }
            });

            //Set Completed time
            var header = await _context.CalculationHeaders.FindAsync(message.HeaderId);

            header.CompletedTime = DateTime.Now;
            header.Status        = "Processed";
            _context.Update(header);
            await _context.SaveChangesAsync();

            //Bulk perfoms better for large records
            _context.BulkInsert(result.Select(r => new CalculationResult {
                CalculationHeaderId = message.HeaderId,
                Formular            = r.Formula, InputA = r.A, InputB = r.B, InputC = r.C, Result = Math.Round(r.Result, 2)
            }).ToList());

            if (errors.Any())
            {
                _context.BulkInsert(errors);
            }
        }