예제 #1
0
        public async Task <IActionResult> UploadLecturerFile(IFormFile file)
        {
            var uploadFolderPath = Path.Combine(host.ContentRootPath, "uploads/lecturer");

            if (!Directory.Exists(uploadFolderPath))
            {
                Directory.CreateDirectory(uploadFolderPath);
            }

            if (file == null)
            {
                return(BadRequest("STOP HACKING OUR WEBSITE. SEND A FILE FOR US TO EXECUTE, PLEASE"));
            }

            if (file.Length == 0)
            {
                return(BadRequest("DO YOU THINK A EMPTY FILE CAN CRASH OUR WEBSITE"));
            }

            if (file.Length > MAX_BYTES)
            {
                return(BadRequest("PLEASE CHOOSE A FILE WHICH SIZE < 10 MB. OUR SYSTEM IS TOO BUSY TO DO EXECUTE THIS FILE"));
            }

            if (!ACCEPTED_FILE_TYPES.Any(s => s == Path.GetExtension(file.FileName.ToLower())))
            {
                return(BadRequest("ARE YOU HAPPY WHEN DO THAT. CHOOSE VALID TYPE, PLEASE"));
            }

            var fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
            var filePath = Path.Combine(uploadFolderPath, fileName);

            //create excel
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }

            // add students
            using (ExcelPackage package = new ExcelPackage(new FileInfo(filePath)))
            {
                ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
                int            rowCount  = worksheet.Dimension.Rows;
                try
                {
                    for (int row = 3; row <= rowCount; row++)
                    {
                        var val = worksheet.Cells[row, 2].Value;
                        if (val == null)
                        {
                            break;
                        }
                        else
                        {
                            Lecturer lecturer = new Lecturer();
                            await excelRepository.AddLecturer(lecturer, worksheet, row);

                            lecturerRepository.AddLecturer(lecturer);
                        }
                        await unitOfWork.Complete();
                    }
                }
                catch (Exception ex)
                {
                    return(BadRequest("CHECK YOUR FILE AGAIN, PLEASE. SOME WRONG WITH THIS FILE"
                                      + "\n" + "Detail: " + ex.Message));
                }
            }

            //add to db
            var excel = new Excel {
                FileName = fileName
            };

            excelRepository.AddExcel(excel);
            await unitOfWork.Complete();

            return(Ok(mapper.Map <Excel, ExcelResource>(excel)));
        }