コード例 #1
0
        public IActionResult Upload(string year, IFormFile file)
        {
            if (file == null)
            {
                return(new BadRequestObjectResult(
                           new ErrorResponse($"Could not find parameter named '{nameof(file)}'.")));
            }

            if (!_parsers.ContainsKey(file.ContentType))
            {
                return(new BadRequestObjectResult(
                           new ErrorResponse($"Invalid file Content-Type '{file.ContentType}'.")));
            }

            var input    = _parsers[file.ContentType](year, file.OpenReadStream());
            var username = User.FindFirst(c => c.Type == JwtRegisteredClaimNames.Sub).Value;

            Calendar calendar;

            using (var tx = _context.Database.BeginTransaction())
            {
                try
                {
                    calendar = _calendars.Get(input.SchoolYear);
                    if (calendar == null)
                    {
                        calendar             = input;
                        calendar.Created     = DateTime.Now;
                        calendar.LastUpdated = calendar.Created;
                        _context.Add(calendar);
                    }
                    else
                    {
                        var details = new List <AuditDetail>();
                        var added   = input.Days.Where(id => !calendar.Days.Any(cd => cd.Date == id.Date));
                        Console.WriteLine("Added:");
                        foreach (var add in added)
                        {
                            Console.WriteLine($"\t{add.Date}");
                        }

                        foreach (var add in added)
                        {
                            details.Add(new AuditDetail
                            {
                                Field = "Day",
                                Next  = add.Date.ToString("MM/dd/yyyy"),
                            });
                        }

                        var removed = calendar.Days.Where(cd => !input.Days.Any(id => id.Date == cd.Date));
                        Console.WriteLine("Removed:");
                        foreach (var remove in removed)
                        {
                            Console.WriteLine($"\t{remove.Date}");
                        }

                        foreach (var remove in removed)
                        {
                            details.Add(new AuditDetail
                            {
                                Field    = "Day",
                                Previous = remove.Date.ToString("MM/dd/yyyy"),
                            });
                        }

                        _context.Remove(calendar);
                        input.Created     = calendar.Created;
                        input.LastUpdated = DateTime.Now;
                        _context.Add(input);
                        calendar = input;
                        _audits.Create(new AuditHeader
                        {
                            Username   = username,
                            Activity   = AuditActivity.UPDATE_SCHOOL_CALENDAR,
                            Timestamp  = DateTime.Now,
                            Identifier = calendar.SchoolYear,
                            Details    = details,
                        });
                    }

                    _context.SaveChanges();
                    tx.Commit();
                }
                catch (Exception)
                {
                    tx.Rollback();
                    throw;
                }
            }

            return(new CreatedResult($"/api/calendars/{year}", new CalendarResponse
            {
                Calendar = calendar,
            }));
        }
コード例 #2
0
        private static void HandleFileChange(object source, FileSystemEventArgs e)
        {
            try
            {
                _processing.WaitOne();

                _context = new PacBillContext(new DbContextOptionsBuilder <PacBillContext>().
                                              UseSqlServer(_connectionString).Options);

                using (var tx = _context.Database.BeginTransaction())
                {
                    string scope;
                    if (IsRecon(e.Name))
                    {
                        scope = GetReconScope();
                    }
                    else
                    {
                        scope = GetMonthlyScope(_context);
                    }

                    Console.WriteLine($"Scope: {scope}");

                    var header = _context.StudentRecordsHeaders.Include(r => r.Records).SingleOrDefault(h => h.Scope == scope);
                    if (header != null)
                    {
                        if (!header.Locked)
                        {
                            Console.WriteLine($"Data for {scope} exists and is not locked. Overwriting.");
                            _context.Remove(header);
                        }
                        else
                        {
                            Console.WriteLine($"Data for {scope} exists and is locked. Aborting import.");
                            return;
                        }
                    }
                    else
                    {
                        header = new StudentRecordsHeader
                        {
                            Scope    = scope,
                            Filename = e.Name,
                            Created  = DateTime.Now,
                            Locked   = false,
                        };
                    }

                    try
                    {
                        using (var streamReader = File.OpenText(e.FullPath))
                        {
                            var lastWrite = File.GetLastWriteTime(e.FullPath);
                            _parser.Parse(lastWrite, streamReader, header);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Failed to read CSV: {ex.Message}.");
                        if (ex.InnerException != null)
                        {
                            Console.WriteLine($"  Inner exception: {ex.InnerException.Message}.");
                        }

                        return;
                    }

                    try
                    {
                        Console.WriteLine("Writing changes to the database...");
                        if (header.Id == 0)
                        {
                            _context.Add(header);
                        }
                        else
                        {
                            _context.Update(header);
                        }

                        _context.SaveChanges();

                        Console.WriteLine("Writing changes to the database done!");
                        tx.Commit();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Failed to write data to database: {ex.Message}.");
                        if (ex.InnerException != null)
                        {
                            Console.WriteLine($"  Inner exception: {ex.InnerException.Message}.");
                        }

                        return;
                    }
                }
            }
            finally
            {
                _processing.Set();
            }
        }