public async Task <ActionResult <int> > UploadFile([FromForm] IFormFile file, CancellationToken cancellationToken) { //var formFile = Request.Form.Files[0]; if (file == null) { return(BadRequest()); } if (file.ContentType == "application/pdf") { using var memoryStream = new MemoryStream(); await file.CopyToAsync(memoryStream, cancellationToken); if (memoryStream.Length < 262144) { _ = new AppFile { Content = memoryStream.ToArray() }; return(Ok(12134)); } return(BadRequest()); } return(BadRequest()); }
static void Main(string[] args) { Console.WriteLine("SUP Updater"); Console.WriteLine("Copyright (c) 2014 Samarjeet Singh"); if (args.Length < 3) { ShowHelp(); return; } uphost = new ConsoleAppUpdate(); uphost.UpdateFile = args[1]; uphost.Files = AppFile.GetAppFiles(args[0]); uphost.CurrentVersion = Convert.ToDouble(args[2]); print("SUP Updater Console"); print("Copyright (C) 2014 Samarjeet Singh"); print(string.Empty); print("Checking for Updates....."); var checker = new Updater(uphost); if (checker.IsUpdateAvailable()) { var result = MessageBox.Show("Updates are available ? Would you like to download it ?"); if (result == DialogResult.OK) { Update update = checker.GetUpdate(); update.UpdateDownload += update_UpdateDownload; update.DownloadUpdate(); } } else { MessageBox.Show("No Updates Are Available!"); } }
public IActionResult AddNews(string name, string txtdata, IFormFile file) { if (file.ContentType.Contains("image") && name != null && txtdata != null) { string ext = "png"; var File = new AppFile() { FileName = (name + '.' + ext), FileExtansion = ext }; using (var reader = new BinaryReader(file.OpenReadStream())) { byte[] data = reader.ReadBytes((int)file.Length); File.FileSize = String.Format(new FileSizeFormatProvider(), "{0:fs}", data.LongLength); File.Value = data; } Files.AddFile(File); News.AddNews(new News() { Name = name, TextData = txtdata, PublicationDate = DateTime.Now }); return(Ok()); } return(StatusCode(404)); }
private void button3_Click(object sender, EventArgs e) { try { Progress_Init(AppDirectory.LIST.Length + AppFile.LIST.Length); for (int i = 0; i < AppDirectory.LIST.Length; i++) { textBox2.Text += "יוצר תיקיה: " + AppDirectory.GetDirectory(AppDirectory.LIST[i]); Directory.CreateDirectory(AppDirectory.GetDirectory(AppDirectory.LIST[i])); Progress_Add(); textBox2.Text += "נוצרה בהצלחה."; textBox2.ScrollToCaret(); } for (int i = 0; i < AppFile.LIST.Length; i++) { textBox2.Text += "יוצר קובץ: " + AppFile.GetFile(AppFile.LIST[i]); File.WriteAllText(AppFile.GetFile(AppFile.LIST[i]), AppFile.GetFileDefaultText(AppFile.LIST[i])); Progress_Add(); textBox2.Text += "נוצר בהצלחה."; } } catch (Exception ex) { Classes.App.Error("בעיה בהפעלת חלק " + progressBar1.Value + " של ההתקנה:\r\n" + ex.Message, true); } finally { button1.Enabled = true; button2.Enabled = false; button3.Enabled = false; System.Media.SystemSounds.Exclamation.Play(); } }
internal static void CleanupOldFiles(AppFile appFile) { try { FileType fileType = FileType.GetFileType(appFile); foreach (var file in Directory.EnumerateFiles(fileType.Directory, $"{fileType.FilePrefix}*")) { try { FileInfo fI = new FileInfo(file); if (fI.LastWriteTime < DateTime.Now.AddDays(-fileType.RetentionDays)) { Log.Debug($"Deleting old {fileType.AppFile} file: {fI.Name}"); fI.Delete(); Log.Information($"Deleted old {fileType.AppFile} file: {fI.Name}"); } else { Log.Debug($"Skipping file that doesn't fall within dateTime constraints: {fI.LastWriteTime} | {fI.Name}"); } } catch (Exception ex) { Log.Warning(ex, "Failed to process old file"); } } } catch (Exception ex) { Log.Error(ex, "Failed to cleanup old {FileName} files", appFile); Handler.NotifyError(ex, "FileCleanup"); } }
public async Task AddFileAsync(DataToChange dataToChange) { var dataContext = DataContext; foreach (var file in dataToChange.Files) { if (IsNotExtensionValid(file)) { return; } using var memoryStream = new MemoryStream(); await file.CopyToAsync(memoryStream); if (memoryStream.Length > 5242880) { return; } var appFile = new AppFile() { StageId = dataToChange.StageId, Name = file.FileName, Type = file.ContentType, Content = memoryStream.ToArray() }; dataContext.Files.Add(appFile); //TODO: Надеюсь, что будет незаметно.; await dataContext.SaveChangesAsync(); _logger.LogInformation("Время: {TimeAction}. Пользователь(Id:{ExecutorId}) , {Status} файл(Id:{FileId}) в Проекте (Id:{ProjectId})", DateTime.Now, dataToChange.CurrentUserId, Status.Created, appFile.Id, dataToChange.ProjectId); } }
public async Task CreateAsyncTest() { var movieStub = new Movie() { Name = "TEST_MOVIE", Genre = MovieGenre.Action }; var posterStub = new AppFile() { FileName = "TEST_FILE", Content = null }; _filesServiceMock .Setup(x => x.Save(It.IsAny <string>(), It.IsAny <byte[]>())) .Verifiable(); _moviesRepositoryMock .Setup(x => x.AddAsync(It.IsAny <Movie>())) .ReturnsAsync(new Movie()) .Verifiable(); var result = await _service.CreateAsync(movieStub, posterStub); _filesServiceMock.VerifyAll(); _moviesRepositoryMock.VerifyAll(); }
public async Task <IActionResult> OnPostUploadAsync() { // Perform an initial check to catch FileUpload class // attribute violations. if (!ModelState.IsValid) { Result = "Please correct the form."; return(Page()); } foreach (var formFile in FileUpload.FormFiles) { var formFileContent = await FileHelpers.ProcessFormFile <BufferedMultipleFileUploadDb>( formFile, ModelState, _permittedExtensions, _fileSizeLimit); // Perform a second check to catch ProcessFormFile method // violations. If any validation check fails, return to the // page. if (!ModelState.IsValid) { Result = "Please correct the form."; return(Page()); } // Don't trust the file name sent by the client. Use Linq to // remove invalid characters. Another option is to use // Path.GetRandomFileName to generate a safe random // file name. var invalidFileNameChars = Path.GetInvalidFileNameChars(); var fileName = invalidFileNameChars.Aggregate( formFile.FileName, (current, c) => current.Replace(c, '_')); // **WARNING!** // In the following example, the file is saved without // scanning the file's contents. In most production // scenarios, an anti-virus/anti-malware scanner API // is used on the file before making the file available // for download or for use by other systems. // For more information, see the topic that accompanies // this sample. var file = new AppFile() { Content = formFileContent, Name = fileName, Note = FileUpload.Note, Size = formFile.Length, UploadDT = DateTime.UtcNow }; _context.File.Add(file); await _context.SaveChangesAsync(); } return(RedirectToPage("./Index")); }
public async Task <IActionResult> PutAppFile(int id, AppFile appFile) { if (id != appFile.Id) { return(BadRequest()); } _context.Entry(appFile).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!AppFileExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <IActionResult> OnPostUploadAsync() { using (memoryStream = new MemoryStream()) { await FileUpload.FormFile.CopyToAsync(memoryStream); // Upload the file if less than 50 MB if (memoryStream.Length < 5068435456) { var file = new AppFile() { Content = memoryStream.ToArray() }; newAppFile = new AppFile(); _3DPS RequestDirector = new _3DPS(); bool confirmation; file.FileName = FileUpload.FormFile.FileName; file.FileType = Path.GetExtension(FileUpload.FormFile.FileName); file.ColorName = ColorSelect; file.Comments = Comments; confirmation = RequestDirector.UploadAppFile(file); FileList = RequestDirector.GetAppFiles(); } else { ModelState.AddModelError("File", "The file is too large."); } } Message = "File successfully uploaded!"; return(Page()); }
public async Task <IActionResult> Upload([FromForm] FileUploadViewModel model) { try { using (var memoryStream = new MemoryStream()) { await model.FormFile.CopyToAsync(memoryStream); var file = new AppFile() { Content = memoryStream.ToArray(), Name = model.FormFile.FileName }; _context.File.Add(file); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } } catch (Exception ex) { return(RedirectToAction(nameof(Error))); } }
public string GenerateUniqueFileName(AppFile file, IUniqueCharsGenerator generator, UniqueCharsPosition position) { if (file == null) { throw new ArgumentNullException("file"); } if (generator == null) { throw new ArgumentNullException("generator"); } string uniqueID = generator.Generate(); StringBuilder sb = new StringBuilder(); if (position == UniqueCharsPosition.Prefix) { sb.AppendFormat("{0}_", uniqueID); } sb.AppendFormat("{0}", file.FileNameWithoutExtension); if (position == UniqueCharsPosition.Suffix) { sb.AppendFormat("_{0}", uniqueID); } sb.AppendFormat("{0}", file.FileExtension); return sb.ToString(); }
public async Task <IActionResult> UploadFile() { var formFile = Request.Form.Files[0]; var filename = Request.Form.FirstOrDefault(k => k.Key == "FileName").Value; var ext = Path.GetExtension(filename).ToLowerInvariant(); if (string.IsNullOrEmpty(ext) || !permittedExtensions.Contains(ext)) { return(BadRequest("Invalid file extension")); } try { using (var memoryStream = new MemoryStream()) { await formFile.CopyToAsync(memoryStream); var file = new AppFile { FileName = WebUtility.HtmlEncode(filename), OwnerId = User.Claims.FirstOrDefault(claim => claim.Type == ClaimTypes.NameIdentifier).Value, TopicId = int.Parse(Request.Form.FirstOrDefault(k => k.Key == "TopicId").Value), Content = memoryStream.ToArray() }; _context.FileList.Add(file); await _context.SaveChangesAsync(); } return(Created("File is uploaded", "")); } catch (DbUpdateException) { return(StatusCode(406)); } }
private void PrivatePanel_Load(object sender, EventArgs e) { textBox1.Text = File.ReadAllText(AppFile.GetFile(AppFile.MARQUEE), Encoding.UTF8); string[] list = Directory.GetFiles(AppDirectory.GetDirectory(AppDirectory.INFO)); FileInfo tmp; for (int i = 0; i < list.Length; i++) { tmp = new FileInfo(list[i]); listBox1.Items.Add(tmp.Name); files.Add(list[i]); } label13.Text = CurrentUser.ID; DataRow row = Classes.SQL.Select("Teachers", "tid", CurrentUser.ID).Rows[0]; label5.Text = row["firstname"].ToString(); label7.Text = row["lastname"].ToString(); label9.Text = Classes.App.GenderName(Convert.ToInt32(row["gender"])); label11.Text = Classes.Duty.GetName(row["dutyid"].ToString()); textBox4.Text = row["phone"].ToString(); textBox3.Text = row["password"].ToString(); pictureBox1.Image = File.Exists(pic) ? Image.FromFile(pic) : Images.NoImage; DataTable ts = Classes.Teacher.List(); for (int i = 0; i < ts.Rows.Count; i++) { teachers.Add(ts.Rows[i]["tid"].ToString()); dataGridView1.Rows.Add(new object[] { ts.Rows[i]["firstname"].ToString() + " " + ts.Rows[i]["lastname"].ToString(), Classes.Duty.GetName(ts.Rows[i]["dutyid"].ToString()), ts.Rows[i]["phone"].ToString() }); } }
public void DeleteFile(AppFile file) { if (file != null) { _fileSystem.DeleteFile(file.FilePath); } }
public void Add(IDalAppFile entity) { if (entity == null) { throw new ArgumentNullException("entity"); } var file = new AppFile() { Id = entity.Id, Content = entity.Content, DateUploaded = entity.DateUploaded, Name = entity.Name, ContentType = entity.ContentType, Size = entity.Size }; file.User = _context.Set <User>().Find(entity.UserId); if (entity.FolderId != null) { file.Folder = _context.Set <AppFolder>().Find(entity.FolderId); } _context.Set <AppFile>().Add(file); }
/// <summary> /// Reads the file content and store it in an object in an In-Memory DB /// </summary> /// <param name="formFile">File content sent with Request</param> /// <returns>true, if processed successfully else false</returns> public async Task <bool> Process(IFormFile formFile) { try { using var memoryStream = new MemoryStream(); await formFile.CopyToAsync(memoryStream); var file = new AppFile { Id = Guid.NewGuid().ToString(), Content = memoryStream.ToArray(), ContentType = formFile.ContentType, EncodedName = WebUtility.HtmlEncode(formFile.FileName), Size = formFile.Length, UploadDate = DateTime.UtcNow }; _context.File.Add(file); await _context.SaveChangesAsync(); return(true); } catch (Exception ex) { _logger.LogError(ex, $"{nameof(DocumentRepository)}: Error occurred processing the file {formFile.FileName}"); } return(false); }
public async Task <AppFile> UploadFileAsync(HttpPostedFile file) { try { Stream streamFile = file.InputStream; RegionEndpoint bucketRegion = RegionEndpoint.GetBySystemName(regionName); IAmazonS3 s3Client = new AmazonS3Client(key, secretKey, bucketRegion); var fileTransferUtility = new TransferUtility(s3Client); Guid guid = Guid.NewGuid(); TransferUtilityUploadRequest request = new TransferUtilityUploadRequest(); request.BucketName = bucketName; request.Key = string.Format(filePath, guid, file.FileName); request.InputStream = streamFile; await fileTransferUtility.UploadAsync(request); int id = Insert("/" + request.Key, file.FileName); AppFile responseObj = new AppFile(); responseObj.Id = id; responseObj.Path = Convert.ToString(_keysService.GetByKeyName <string>("AWS.PathLink")) + "/" + request.Key; return(responseObj); } catch (AmazonS3Exception e) { Console.WriteLine("Error encountered on server. Message:'{0}' when writing an object", e.Message); return(null); } catch (Exception e) { Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message); return(null); } }
private void ReportProgress(AppFile file, ref int index, int filesCount) { int percentageDone = (int)(100.0 / filesCount * index); _backgroundWorker.ReportProgress(percentageDone, file); ++index; }
public async Task <Response <AppFileModel> > Save([FromBody] AppFileModel appFileModel) { Response <AppFileModel> appFileModelResponse = new Response <AppFileModel>(); try { AppFile appFile = _mapper.Map <AppFile>(appFileModel); BlobManager <AppFile> manager = new BlobManager <AppFile>(); CloudBlobContainer container = await manager.CreateFolderAsync(appFile); if (string.IsNullOrEmpty(appFile.BlobPath)) { CloudBlockBlob cloudBlockBlob = await manager.UploadFileAsync(container, appFile); appFile.BlobPath = $"{cloudBlockBlob.Parent.Prefix}"; appFile.BlobPath = $"{ Configuration.ConfigurationManager.Instance.GetValue("FileUploadBlobContainer")}/{appFile.BlobPath.Substring(0, appFile.BlobPath.Length - 1) }"; } appFile = await(appFileModel.Id != Guid.Empty ? _appFile.UpdateAsync(appFile) : _appFile.AddAsync(appFile)); AppFileModel model = _mapper.Map <AppFileModel>(appFile); appFileModelResponse.Value = model; } catch (Exception ex) { appFileModelResponse.Exception = ex; appFileModelResponse.IsSuccess = false; } return(appFileModelResponse); }
public IActionResult AddFile(AddFileViewModel model) { if (ModelState.IsValid) { if (repository.AllFiles.Any(x => x.FileName == model.File.FileName)) { ModelState.AddModelError("", "File with name " + model.File.FileName + " is alredy exist."); return(View(model)); } var directory = Directory.GetFiles(environment.ContentRootPath + @"/wwwroot/FileExtansions"); var ext = new String(model.File.FileName.TakeLast(model.File.FileName.Length - (model.File.FileName.LastIndexOf('.') == -1 ? model.File.FileName.Length : model.File.FileName.LastIndexOf('.')) - 1).ToArray()); if (!directory.Any(x => x == ("File" + ext + ".png"))) { ext = ""; } var File = new AppFile() { FileName = model.File.FileName, FileExtansion = ext }; using (var reader = new BinaryReader(model.File.OpenReadStream())) { byte[] data = reader.ReadBytes((int)model.File.Length); File.FileSize = String.Format(new FileSizeFormatProvider(), "{0:fs}", data.LongLength); File.Value = data; } repository.AddFile(File); return(LocalRedirect(model.ReturnUrl)); } return(View(model)); }
public string GenerateUniqueFileName(AppFile file, IUniqueCharsGenerator generator, UniqueCharsPosition position) { if (file == null) { throw new ArgumentNullException("file"); } if (generator == null) { throw new ArgumentNullException("generator"); } string uniqueID = generator.Generate(); StringBuilder sb = new StringBuilder(); if (position == UniqueCharsPosition.Prefix) { sb.AppendFormat("{0}_", uniqueID); } sb.AppendFormat("{0}", file.FileNameWithoutExtension); if (position == UniqueCharsPosition.Suffix) { sb.AppendFormat("_{0}", uniqueID); } sb.AppendFormat("{0}", file.FileExtension); return(sb.ToString()); }
public static async Task <AppFileValue> SaveImage(this TDContext db, string ImageData, string Path, string id = null) { AppFile find = null; if (id != null && id.Length > 0) { find = await db.AppFiles.FindAsync(id); } if (find == null) { var saveFile = ImageData.WriteImageString(Path); if (!saveFile.Success) { return(AppFileValue.Error(saveFile.Message)); } find = new AppFile(new DBHelper().GetAppFileId(db), saveFile.FileName); find.UploadType = UploadType.Image; find.FullPath = saveFile.Output.Replace(HttpContext.Current.Server.MapPath("~"), "").Replace("\\", "/"); db.AppFiles.Add(find); } else { var filepath = HttpContext.Current.Server.MapPath("~" + find.FullPath); var saveFile = ImageData.WriteImageString(null, filepath); if (!saveFile.Success) { return(AppFileValue.Error(saveFile.Message)); } find.FileName = saveFile.FileName; find.UploadType = UploadType.Image; find.FullPath = saveFile.Output.Replace(HttpContext.Current.Server.MapPath("~"), "").Replace("\\", "/"); db.Entry(find).State = EntityState.Modified; } return(AppFileValue.Success(find)); }
public async Task <ActionResult <AppFile> > PostAppFile(AppFile appFile) { _context.File.Add(appFile); await _context.SaveChangesAsync(); return(CreatedAtAction("GetAppFile", new { id = appFile.Id }, appFile)); }
public override async void OnNavigatedTo(INavigationParameters param) { if (Ds.NeedInit) { var path = AppFile.GetPath(); path = Path.Combine(path, AppUtils.DbName); await Ds.Init(path); } var runTimer5 = param?[nameof(NavParamEnum.RunTimer5)] as bool?; if (runTimer5 != null && (bool)runTimer5) { var objGameName = param?[nameof(NavParamEnum.GameName)]; if (objGameName != null) { _gameName = objGameName.ToString(); if (_timer == null) { _timer = new ActionTimer(); _timer.InitAndStart(ShowMess); } else { _timer.Restart(); } } } await InitGames(); }
public static FileType GetFileType(AppFile appFile) { return(appFile switch { AppFile.Config => new FileType { AppFile = AppFile.Config, FilePrefix = "Config_", Directory = Constants.PathConfigDefault, RetentionDays = 7 }, AppFile.Log => new FileType { AppFile = AppFile.Log, FilePrefix = OSDynamic.GetProductAssembly().ProductName, Directory = Constants.PathLogs, RetentionDays = 30 }, AppFile.SavedData => new FileType { AppFile = AppFile.SavedData, FilePrefix = "SaveData_", Directory = Constants.PathSavedData, RetentionDays = 90 }, _ => new FileType { AppFile = AppFile.Log, FilePrefix = OSDynamic.GetProductAssembly().ProductName, Directory = Constants.PathLogs, RetentionDays = 30 }, });
public void Run_SupplyFiveFilesAndFirstFileAlreadyExistsAndItShouldBeOverwritten_FirstFileIsOverwritten() { // arrange List <AppFile> filesToCopy = InitializeFiles(); string pathTo = "Z:/dummy_folder"; string existingFilePath = string.Format("{0}/{1}", pathTo, filesToCopy[0].FileNameFull); string sourceFilePath = filesToCopy[0].FilePath; AppFile currentFile = new AppFile(); fileHelperMock.Setup(x => x.GenerateUniqueFileName(It.IsAny <AppFile>(), It.IsAny <IUniqueCharsGenerator>(), It.IsAny <UniqueCharsPosition>())) .Callback <AppFile, IUniqueCharsGenerator, UniqueCharsPosition>((a, b, c) => { currentFile = a; }) .Returns(() => currentFile.FileNameFull); fileSystemMock.Setup(s => s.FileExists(existingFilePath)).Returns(true); fileSystemMock.Setup(s => s.DeleteFile(existingFilePath)); fileSystemMock.Setup(s => s.CopyTo(It.IsAny <string>(), It.IsAny <string>())); settingsMock.Setup(s => s.FilesToCopy).Returns(filesToCopy); settingsMock.SetupGet(s => s.OnDuplicateOverwrite).Returns(true); settingsMock.SetupGet(s => s.PathTo).Returns(pathTo); // act _worker.Run(_parameters); _backgroundWorkerMock.Raise(x => { x.OnDoWork += null; }, null, new System.ComponentModel.DoWorkEventArgs(null)); // assert fileSystemMock.Verify(x => x.DeleteFile(existingFilePath), Times.Once()); fileSystemMock.Verify(x => x.CopyTo(sourceFilePath, existingFilePath), Times.Once()); settingsMock.VerifyGet(x => x.OnDuplicateOverwrite, Times.Once()); }
public void GetFilesByMaxFileSize_NonUniqueFiles_SupplyFilesAndExistingFilesAndSizeLimit_ReturnsNonUniqueAndNonExistingRandomFilesLessOrEqualToMaximumSizeLimit(double[] fileSizes, double[] existingFileSizes, double sizeLimit, int expectedFilesCount) { // arrange InitializeMocks(); FileService fileService = InitializeConstructor(); List <AppFile> files = null; if (fileSizes != null) { files = new List <AppFile>(); foreach (double fileSize in fileSizes) { files.Add(new AppFile { FileNameFull = "file", FileSize = fileSize }); } } List <AppFile> existingFiles = null; if (existingFileSizes != null) { existingFiles = new List <AppFile>(); foreach (double fileSize in existingFileSizes) { existingFiles.Add(new AppFile { FileNameFull = "file", FileSize = fileSize }); } } List <AppFile> returnedFiles = new List <AppFile>(); fileHelperMock.Setup(x => x.GetRandomFile(It.IsAny <IEnumerable <AppFile> >())).Returns <IEnumerable <AppFile> >((collection) => { AppFile fileToReturn = null; fileToReturn = collection.Where(x => !returnedFiles.Contains(x)).FirstOrDefault(); if (fileToReturn == null) { fileToReturn = collection.First(); } returnedFiles.Add(fileToReturn); return(fileToReturn); }); // act IEnumerable <AppFile> result = fileService.GetFilesByMaxFileSize(false, files, existingFiles, sizeLimit); // assert Assert.AreEqual(expectedFilesCount, result.ToList().Count); }
public static DalAppFile ToDalAppFile(this AppFile file) { if (file == null) { return(null); } return((DalAppFile)DalMappersExpressions.ToDalAppFileExpression().Compile()(file)); }
private static void LoadSettingsClass(Type settingsType, string settingsFileAppPath) { if (AppFile.Exists(settingsFileAppPath)) { var settings = YamlDeserializer.Deserialize <Dictionary <string, object> >(AppFile.ReadAllText(settingsFileAppPath)); ReflectionHelper.PopulatePublicStaticProperties(settingsType, settings); } }
public async Task <IActionResult> DownloadFileAsync(int fileId) { GetInformation(); DataToChange.FileId = fileId; AppFile file = await _dataRepository.GetFileAsync(DataToChange); return(File(file.Content, file.Type, file.Name)); }
public void Equals_CompareSameInstance_ReturnsTrue() { // arrange AppFile file = new AppFile(); // act bool result = comparer.Equals(file, file); // assert Assert.IsTrue(result); }
public void Equals_CompareNullInstanceToNonNullInstance_ReturnsFalse() { // arrange AppFile file = new AppFile(); // act bool result = comparer.Equals(null, file); // assert Assert.IsFalse(result); }
public AppFile CreateAppFile(string filePath) { FileInfo fileInfo = new FileInfo(filePath); AppFile file = new AppFile(); file.FileNameFull = fileInfo.Name; file.FileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePath); file.FilePath = fileInfo.FullName; file.FileSize = fileInfo.Length; file.FileExtension = fileInfo.Extension; return file; }
public void Equals_CompareInstancesByTheirFileNameFullAndFileSizeProperties_ReturnsExpectedResult(string fileNameFullOne, string fileNameFullTwo, double fileSizeOne, double fileSizeTwo, bool expectedResult) { // arrange AppFile fileOne = new AppFile { FileNameFull = fileNameFullOne, FileSize = fileSizeOne }; AppFile fileTwo = new AppFile { FileNameFull = fileNameFullTwo, FileSize = fileSizeTwo }; // act bool result = comparer.Equals(fileOne, fileTwo); // assert Assert.AreEqual(expectedResult, result); }
public void GetHashCode_ExecuteFunctionForTwoObjectsWithTheSameProperties_ReturnsEqualHashcodes(string fileNameFull, double fileSize) { // arrange AppFile fileOne = new AppFile { FileNameFull = fileNameFull, FileSize = fileSize }; AppFile fileTwo = new AppFile { FileNameFull = fileNameFull, FileSize = fileSize }; // act int fileOneHashCode = comparer.GetHashCode(fileOne); int fileTwoHashCode = comparer.GetHashCode(fileTwo); // assert Assert.AreEqual(fileOneHashCode, fileTwoHashCode); }
public void GetHashCode_ExecuteFunctionForTwoObjectsWithDifferentProperties_ReturnsDifferentHashcodes(string fileNameFullOne, double fileSizeOne, string fileNameFullTwo, double fileSizeTwo) { // arrange AppFile fileOne = new AppFile { FileNameFull = fileNameFullOne, FileSize = fileSizeOne }; AppFile fileTwo = new AppFile { FileNameFull = fileNameFullTwo, FileSize = fileSizeTwo }; // act int fileOneHashCode = comparer.GetHashCode(fileOne); int fileTwoHashCode = comparer.GetHashCode(fileTwo); // assert Assert.AreNotEqual(fileOneHashCode, fileTwoHashCode); }
public void OnFileChanged_SetsFileFullNameOnModelProgressText() { SetUp(); AppFile file = new AppFile { FileNameFull = "test" }; _viewModelMock .SetupSet(x => x.ProgressInfoText = It.IsAny<string>()) .Callback<string>(x => Assert.IsTrue(x == file.FileNameFull)); _presenter.OnFileChanged(file); _viewMock.Verify(); }
public void GenerateUniqueFileName_GeneratorArgumentIsNotSupplied_ThrowsGeneratorArgumentNullException() { // arrange FileHelper fileHelper = new FileHelper(); AppFile file = new AppFile(); TestDelegate testDelegate = () => fileHelper.GenerateUniqueFileName(file, null, It.IsAny<UniqueCharsPosition>()); // act, assert Assert.That(testDelegate, Throws.Exception.TypeOf<ArgumentNullException>().With.Property("ParamName").EqualTo("generator")); }
public void GenerateUniqueFileName_SupplyFileAndGeneratorAndPosition_ReturnsFileNameWithExtensionWithProperlyPositionedUniqueString(UniqueCharsPosition position, string expectedResult) { // arrange AppFile file = new AppFile(); file.FileNameFull = "TestFileName.extension"; file.FileNameWithoutExtension = "TestFileName"; file.FileExtension = ".extension"; Mock<IUniqueCharsGenerator> generatorMock = new Mock<IUniqueCharsGenerator>(); generatorMock.Setup(s => s.Generate()).Returns("UniqueCharsSequence"); FileHelper fileHelper = new FileHelper(); // act string result = fileHelper.GenerateUniqueFileName(file, generatorMock.Object, position); //assert Assert.AreEqual(expectedResult, result); }
public void Run_SupplyFiveFilesAndFirstFileAlreadyExistsAndItShouldNotBeCopied_FirstFileIsNotCopied() { // arrange List<AppFile> filesToCopy = InitializeFiles(); string pathTo = "Z:/dummy_folder"; string existingFilePath = string.Format("{0}/{1}", pathTo, filesToCopy[0].FileNameFull); string sourceFilePath = filesToCopy[0].FilePath; AppFile currentFile = new AppFile(); fileHelperMock.Setup(x => x.GenerateUniqueFileName(It.IsAny<AppFile>(), It.IsAny<IUniqueCharsGenerator>(), It.IsAny<UniqueCharsPosition>())) .Callback<AppFile, IUniqueCharsGenerator, UniqueCharsPosition>((a, b, c) => { currentFile = a; }) .Returns(() => currentFile.FileNameFull); fileSystemMock.Setup(s => s.FileExists(existingFilePath)).Returns(true); fileSystemMock.Setup(s => s.CopyTo(It.IsAny<string>(), It.IsAny<string>())); settingsMock.Setup(s => s.FilesToCopy).Returns(filesToCopy); settingsMock.SetupGet(s => s.OnDuplicateDoNotCopy).Returns(true); settingsMock.SetupGet(s => s.PathTo).Returns(pathTo); // act _worker.Run(_parameters); _backgroundWorkerMock.Raise(x => { x.OnDoWork += null; }, null, new System.ComponentModel.DoWorkEventArgs(null)); // assert fileSystemMock.Verify(x => x.CopyTo(sourceFilePath, existingFilePath), Times.Never()); settingsMock.VerifyGet(x => x.OnDuplicateDoNotCopy, Times.Once()); }