Although MVC is my framework of choice Legacy WebForms
applications still exist in the world.
.ASPX file 1 2 3 4 5 6 7 8 9 10 11 12 <div class ="form" > <div > <label > File</label > <asp:FileUpload id ="FileUploadControl" runat ="server" /> </div > </div > <div class ="form form-buttons" > <div > <label > </label > <asp:Button ID ="ImportButton" Text ="Import" runat ="server" OnClick ="ImportButton_Click" /> </div > </div >
Code Behind Here _importFromExcelFileService
is the injected service.
1 2 3 4 5 6 ImportButton_Click if (!Validation( )) return ; var savePath = _importFromExcelFileService.SaveFile(FileUploadControl, Server);
Validation method to separate the concearns using the same _importFromExcelFileService
service.
1 2 3 4 5 6 7 8 9 private bool Validation (){ var validationMessage = _importFromExcelFileService.Validate(FileUploadControl); if (validationMessage != "" ) { Tools.ShowMessage(message, validationMessage, messageType.red); return false ; } return true ;
Service Although this did create a dependancys on System.Web.UI.WebControls.FileUpload
and System.IO.FileInfo
I felt this to be a better design.
Its possible to mock these with SystemWrapper
~ https://stackoverflow.com/questions/1582596/how-do-i-moq-the-system-io-fileinfo-class-or-any-other-class-without-an-inter
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 public class ImportFromExcelFileService : IImportFromExcelFileService { private readonly string _allowedExtension = ".xlsx" ; public string SaveFile (FileUpload fileUploadControl, HttpServerUtility server ) { string filename = Path.GetFileName(fileUploadControl.FileName); var path = server.MapPath("~/WhyIsThisNotBeingReadFromConfig/Tmp" ); if (!Directory.Exists(path)) Directory.CreateDirectory(path); var savePath = Path.Combine(path, Guid.NewGuid() + filename); fileUploadControl.SaveAs(savePath); return savePath; } public string Validate (FileUpload fileUploadControl ) { if (!fileUploadControl.HasFile) return "Please select a file." ; if (new FileInfo(fileUploadControl.FileName).Extension != _allowedExtension) return $"Please supply a file in the format {_allowedExtension} " ; return "" ; } }