public ReadingFromExcelModel GetReadersFromFile(string fileName) { var result = new ReadingFromExcelModel(); //reading from excel var excel = new ExcelQueryFactory(); List<Row> readers; try { excel.FileName = fileName; readers = excel.Worksheet().ToList(); if (readers.Count > 0) { if (!readers[0].ColumnNames.Contains("FirstName") || !readers[0].ColumnNames.Contains("LastName") || !readers[0].ColumnNames.Contains("Address") || !readers[0].ColumnNames.Contains("Birthday") || !readers[0].ColumnNames.Contains("Email") || !readers[0].ColumnNames.Contains("Telephone")) { throw new Exception(); } } } catch { throw new ArgumentException("Invalid input file structure!"); } for (int i = 0; i < readers.Count(); i++) { var validationResult = this.ValidateExcelRow(readers[i]); if (validationResult.MemberNames.Count() == 0) { var readerBm = new ReaderBusinessModel(); readerBm.FirstName = readers[i]["FirstName"]; readerBm.LastName = readers[i]["LastName"]; readerBm.Address = readers[i]["Address"]; readerBm.Birthday = readers[i]["Birthday"].Cast<DateTime>(); readerBm.EMail = readers[i]["Email"]; readerBm.Phone = readers[i]["Telephone"]; result.Readers.Add(readerBm); } else { validationResult.ErrorMessage = string.Format("Line: {0}", i + 1); result.Errors.Add(validationResult); } } return result; }
public string GenerateErrorString(ReadingFromExcelModel model) { var errors = string.Empty; if (model.Errors != null) { errors = "Errors: " + Environment.NewLine; foreach (var error in model.Errors) { errors += error.ErrorMessage + " incorrect: "; foreach (var name in error.MemberNames) { errors += name + " "; } errors += Environment.NewLine; } } return errors; }
public HttpResponseMessage AddReadersFromFile() { HttpPostedFile myFile = HttpContext.Current.Request.Files["File"]; var readersFromFile = new ReadingFromExcelModel(); string added = string.Empty; string errors = string.Empty; if (myFile != null && myFile.ContentLength != 0) { string pathForSaving = HttpContext.Current.Server.MapPath("~/App_Data/"); string path = Path.Combine(pathForSaving, myFile.FileName); try { if (!path.EndsWith(ExcelFormat)) { throw new Exception("incorrect file type"); } myFile.SaveAs(path); readersFromFile = this.excelManager.GetReadersFromFile(path); } catch (Exception ex) { var errorResult = new { errors = string.Format("File upload failed: {0}", ex.Message), added = string.Empty, isUploaded = true }; return Request.CreateResponse(HttpStatusCode.BadRequest, errorResult); } var addedReaders = this.readerManager.CreateReaders(readersFromFile.Readers); added = "These readers where added: " + Environment.NewLine; foreach (var reader in addedReaders) { added += reader.FirstName + " " + reader.LastName + Environment.NewLine; } errors = this.excelManager.GenerateErrorString(readersFromFile); } var result = new { isUploaded = true, added = added, errors = errors }; return Request.CreateResponse(HttpStatusCode.OK, result); }