Example #1
0
        public async Task <IActionResult> Upload(string type, string year, IFormFile content)
        {
            if (!ReportType.Values().Contains(type))
            {
                return(new BadRequestObjectResult(new ErrorResponse($"Invalid ReportType '{type}'.")));
            }

            if (!new Regex(@"^\d{4}-\d{4}$").IsMatch(year))
            {
                return(new BadRequestObjectResult(new ErrorResponse($"Invalid SchoolYear '{year}'")));
            }

            if (content == null)
            {
                return(new BadRequestObjectResult(
                           new ErrorResponse($"Could not find parameter named '{nameof(content)}'.")));
            }

            if (content.ContentType != ContentTypes.XLSX)
            {
                return(new BadRequestObjectResult(
                           new ErrorResponse($"Invalid file Content-Type '{content.ContentType}'.")));
            }

            Template template;

            using (var ms = new MemoryStream())
            {
                content.OpenReadStream().CopyTo(ms);
                template = new Template
                {
                    ReportType = ReportType.FromString(type),
                    SchoolYear = year,
                    Name       = content.FileName,
                    Content    = ms.ToArray(),
                };
            }

            template = await Task.Run(() => _context.SaveChanges(() => _templates.CreateOrUpdate(template)));

            var username = User.FindFirst(c => c.Type == JwtRegisteredClaimNames.Sub).Value;

            using (var tx = _context.Database.BeginTransaction())
            {
                try
                {
                    _context.SaveChanges(() => _audits.Create(new AuditHeader
                    {
                        Username   = username,
                        Activity   = AuditActivity.UPDATE_TEMPLATE,
                        Timestamp  = DateTime.Now,
                        Identifier = $"{template.ReportType}_{template.SchoolYear}",
                    }));
                    tx.Commit();
                }
                catch (Exception)
                {
                    tx.Rollback();
                    throw;
                }
            }

            return(new CreatedResult($"/api/templates/{template.ReportType}/{template.SchoolYear}", new TemplateResponse
            {
                Template = new TemplateDto(template),
            }));
        }